use tauri::{command, AppHandle, Emitter};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use futures::StreamExt;
use chrono::Timelike;
use lazy_static::lazy_static;


// 引入 CTP 相关模块
use ctp_trade_lib::{get_api_version as ctp_get_api_version, md_api, trader_api};

// 全局状态管理
lazy_static::lazy_static! {
    static ref MD_APIS: Arc<Mutex<HashMap<String, Box<ctp_trade_lib::CThostFtdcMdApi>>>> =
        Arc::new(Mutex::new(HashMap::new()));
    static ref TRADER_APIS: Arc<Mutex<HashMap<String, Box<ctp_trade_lib::CThostFtdcTraderApi>>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储MD API的Stream
    static ref MD_STREAMS: Arc<Mutex<HashMap<String, Box<ctp_trade_lib::md_api::CThostFtdcMdSpiStream>>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储Trader API的Stream
    static ref TRADER_STREAMS: Arc<Mutex<HashMap<String, Box<ctp_trade_lib::trader_api::CThostFtdcTraderSpiStream>>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 跟踪交易API的登录状态
    static ref TRADER_LOGIN_STATUS: Arc<Mutex<HashMap<String, bool>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 跟踪行情API的登录状态
    static ref MD_LOGIN_STATUS: Arc<Mutex<HashMap<String, bool>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储登录结果信息 (session_id -> (success, message))
    static ref LOGIN_RESULTS: Arc<Mutex<HashMap<String, (bool, String)>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 全局请求ID计数器
    static ref REQUEST_ID_COUNTER: Arc<Mutex<i32>> = Arc::new(Mutex::new(1));
    // 全局订单引用计数器
    static ref ORDER_REF_COUNTER: Arc<Mutex<i32>> = Arc::new(Mutex::new(1));
    // 存储订单插入结果 (order_ref -> (success, message))
    static ref ORDER_INSERT_RESULTS: Arc<Mutex<HashMap<String, (bool, String)>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储会话的登录信息
    static ref SESSION_LOGIN_INFO: Arc<Mutex<HashMap<String, CtpAccountConfig>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储结算确认结果 (session_id -> (success, message))
    static ref SETTLEMENT_CONFIRM_RESULTS: Arc<Mutex<HashMap<String, (bool, String)>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 跟踪结算确认状态
    static ref SETTLEMENT_CONFIRM_STATUS: Arc<Mutex<HashMap<String, bool>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储订单的FrontID和SessionID (order_ref -> (front_id, session_id))
    static ref ORDER_FRONT_SESSION_MAP: Arc<Mutex<HashMap<String, (i32, i32)>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // 存储查询到的订单信息
    static ref QUERIED_ORDERS: Arc<Mutex<HashMap<String, Vec<OrderInfo>>>> =
        Arc::new(Mutex::new(HashMap::new()));

    // 存储从CTP回调获取的合约数据
    static ref CTP_INSTRUMENTS_DATA: Arc<Mutex<Vec<InstrumentInfo>>> =
        Arc::new(Mutex::new(Vec::new()));

    // 合约查询状态标记
    static ref INSTRUMENTS_QUERY_COMPLETE: Arc<Mutex<bool>> =
        Arc::new(Mutex::new(false));

    // 全局App Handle用于发送事件到前端
    static ref APP_HANDLE: Arc<Mutex<Option<AppHandle>>> =
        Arc::new(Mutex::new(None));
}

// 数据结构定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CtpAccountConfig {
    pub broker_id: String,
    pub account: String,
    pub password: String,
    pub trade_front: String,
    pub md_front: String,
    pub auth_code: String,
    pub user_product_info: String,
    pub app_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ApiResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub error: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MarketDataRequest {
    pub instrument_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderRequest {
    pub instrument_id: String,
    pub direction: String, // "0" for buy, "1" for sell
    pub price: f64,
    pub volume: i32,
    pub order_type: String, // "1" for limit order, "2" for limit price
    pub offset_flag: Option<String>, // "0" for open, "1" for close
    pub hedge_flag: Option<String>, // "1" for speculation, "2" for arbitrage, "3" for hedge
    pub time_condition: Option<String>, // "1" for IOC, "3" for GFD
    pub volume_condition: Option<String>, // "1" for any volume
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CancelOrderRequest {
    pub order_ref: String,
    pub front_id: Option<i32>,
    pub session_id: Option<i32>,
    pub exchange_id: Option<String>,
    pub order_sys_id: Option<String>,
    pub instrument_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AccountInfo {
    pub broker_id: String,
    pub account_id: String,
    pub pre_mortgage: f64,
    pub pre_credit: f64,
    pub pre_deposit: f64,
    pub pre_balance: f64,
    pub pre_margin: f64,
    pub interest_base: f64,
    pub interest: f64,
    pub deposit: f64,
    pub withdraw: f64,
    pub frozen_margin: f64,
    pub frozen_cash: f64,
    pub frozen_commission: f64,
    pub curr_margin: f64,
    pub cash_in: f64,
    pub commission: f64,
    pub close_profit: f64,
    pub position_profit: f64,
    pub balance: f64,
    pub available: f64,
    pub withdraw_quota: f64,
    pub reserve: f64,
    pub trading_day: String,
    pub settlement_id: i32,
    pub credit: f64,
    pub mortgage: f64,
    pub exchange_margin: f64,
    pub delivery_margin: f64,
    pub exchange_delivery_margin: f64,
    pub reserve_balance: f64,
    pub currency_id: String,
    pub pre_fund_mortgage_in: f64,
    pub pre_fund_mortgage_out: f64,
    pub fund_mortgage_in: f64,
    pub fund_mortgage_out: f64,
    pub fund_mortgage_available: f64,
    pub mortgage_able_fund: f64,
    pub spec_product_margin: f64,
    pub spec_product_frozen_margin: f64,
    pub spec_product_commission: f64,
    pub spec_product_frozen_commission: f64,
    pub spec_product_position_profit: f64,
    pub spec_product_close_profit: f64,
    pub spec_product_position_profit_by_alg: f64,
    pub spec_product_exchange_margin: f64,
    pub bis_margin: f64,
    pub bis_frozen_margin: f64,
    pub bis_commission: f64,
    pub bis_frozen_commission: f64,
    pub bis_position_profit: f64,
    pub bis_close_profit: f64,
    pub bis_position_profit_by_alg: f64,
    pub bis_exchange_margin: f64,
    pub frozen_swap: f64,
    pub remain_swap: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstrumentInfo {
    pub instrument_id: String,
    pub exchange_id: String,
    pub instrument_name: String,
    pub exchange_inst_id: String,
    pub product_id: String,
    pub product_class: String,
    pub delivery_year: i32,
    pub delivery_month: i32,
    pub max_market_order_volume: i32,
    pub min_market_order_volume: i32,
    pub max_limit_order_volume: i32,
    pub min_limit_order_volume: i32,
    pub volume_multiple: i32,
    pub price_tick: f64,
    pub create_date: String,
    pub open_date: String,
    pub expire_date: String,
    pub start_deliv_date: String,
    pub end_deliv_date: String,
    pub inst_life_phase: String,
    pub is_trading: i32,
    pub position_type: String,
    pub position_date_type: String,
    pub long_margin_ratio: f64,
    pub short_margin_ratio: f64,
    pub max_margin_side_algorithm: String,
    pub underlying_inst_id: String,
    pub strike_price: f64,
    pub options_type: String,
    pub underlying_multiple: f64,
    pub combination_type: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PositionInfo {
    pub instrument_id: String,
    pub broker_id: String,
    pub investor_id: String,
    pub posi_direction: String,
    pub hedge_flag: String,
    pub position_date: String,
    pub yd_position: i32,
    pub position: i32,
    pub long_frozen: i32,
    pub short_frozen: i32,
    pub long_frozen_amount: f64,
    pub short_frozen_amount: f64,
    pub open_volume: i32,
    pub close_volume: i32,
    pub open_amount: f64,
    pub close_amount: f64,
    pub position_cost: f64,
    pub pre_margin: f64,
    pub use_margin: f64,
    pub frozen_margin: f64,
    pub frozen_cash: f64,
    pub frozen_commission: f64,
    pub cash_in: f64,
    pub commission: f64,
    pub close_profit: f64,
    pub position_profit: f64,
    pub pre_settlement_price: f64,
    pub settlement_price: f64,
    pub trading_day: String,
    pub settlement_id: i32,
    pub open_cost: f64,
    pub exchange_margin: f64,
    pub comb_position: i32,
    pub comb_long_frozen: i32,
    pub comb_short_frozen: i32,
    pub close_profit_by_date: f64,
    pub close_profit_by_trade: f64,
    pub today_position: i32,
    pub margin_rate_by_money: f64,
    pub margin_rate_by_volume: f64,
    pub strike_frozen: i32,
    pub strike_frozen_amount: f64,
    pub abandon_frozen: i32,
    pub exchange_id: String,
    pub yd_strike_frozen: i32,
    pub invest_unit_id: String,
    pub position_cost_offset: f64,
    pub tas_position: i32,
    pub tas_position_cost: f64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SettlementConfirmRequest {
    pub broker_id: String,
    pub investor_id: String,
    pub confirm_date: String,
    pub confirm_time: String,
}
// 检查订单插入结果
#[command]
pub fn check_order_insert_result(order_ref: String) -> ApiResponse<serde_json::Value> {
    println!("🔍 [DEBUG] check_order_insert_result called with order_ref: {}", order_ref);

    let order_results = ORDER_INSERT_RESULTS.lock().unwrap();

    if let Some((success, message)) = order_results.get(&order_ref) {
        let mut result = serde_json::json!({
            "order_ref": order_ref,
            "success": *success,
            "message": message,
            "status": if *success { "completed" } else { "failed" }
        });

        // 如果订单失败，添加可能的原因和解决方案
        if !*success {
            let suggestions = get_order_rejection_suggestions(message);
            result["suggestions"] = serde_json::json!(suggestions);
        }

        ApiResponse {
            success: true,
            data: Some(result),
            error: None,
        }
    } else {
        let result = serde_json::json!({
            "order_ref": order_ref,
            "success": false,
            "message": "订单结果未找到，可能仍在处理中",
            "status": "pending"
        });

        ApiResponse {
            success: false,
            data: Some(result),
            error: Some("订单结果未找到".to_string()),
        }
    }
}

// 获取订单被拒绝的可能原因和解决方案
fn get_order_rejection_suggestions(error_message: &str) -> Vec<serde_json::Value> {
    let mut suggestions = Vec::new();

    // 根据错误信息提供针对性建议
    if error_message.contains("合约") || error_message.contains("instrument") {
        suggestions.push(serde_json::json!({
            "issue": "合约代码问题",
            "description": "合约代码可能无效或已过期",
            "solutions": [
                "检查合约代码是否正确 (如: a2509, rb2509)",
                "确认合约是否在交易时间内",
                "查询可用合约列表",
                "检查合约是否已到期"
            ]
        }));
    }

    if error_message.contains("价格") || error_message.contains("price") {
        suggestions.push(serde_json::json!({
            "issue": "价格问题",
            "description": "订单价格可能超出限制",
            "solutions": [
                "检查价格是否在涨跌停板范围内",
                "确认价格精度是否符合合约要求",
                "使用市价单避免价格限制",
                "查询合约的最新行情信息"
            ]
        }));
    }

    if error_message.contains("资金") || error_message.contains("margin") {
        suggestions.push(serde_json::json!({
            "issue": "资金不足",
            "description": "账户可用资金不够开仓",
            "solutions": [
                "查询账户资金情况",
                "减少订单数量",
                "平仓释放保证金",
                "入金增加可用资金"
            ]
        }));
    }

    if error_message.contains("时间") || error_message.contains("time") {
        suggestions.push(serde_json::json!({
            "issue": "交易时间问题",
            "description": "可能在非交易时间提交订单",
            "solutions": [
                "确认当前是否在交易时间内",
                "检查合约的交易时间段",
                "等待开盘后重新提交",
                "确认节假日安排"
            ]
        }));
    }

    // 通用建议
    if suggestions.is_empty() {
        suggestions.push(serde_json::json!({
            "issue": "订单被拒绝",
            "description": "订单未能成功提交到交易所",
            "solutions": [
                "检查网络连接是否正常",
                "确认账户状态是否正常",
                "验证订单参数是否正确",
                "联系期货公司客服",
                "查看详细的错误日志"
            ]
        }));
    }

    suggestions
}

// 分析订单被拒绝的原因
#[command]
pub fn analyze_order_rejection(
    session_id: String,
    order: OrderRequest,
) -> ApiResponse<serde_json::Value> {
    println!("🔍 [DEBUG] analyze_order_rejection called with session_id: {}, order: {:?}", session_id, order);

    let mut analysis = serde_json::Map::new();
    let mut issues = Vec::new();
    let mut suggestions = Vec::new();

    // 1. 检查合约代码
    if order.instrument_id.is_empty() {
        issues.push("合约代码为空".to_string());
        suggestions.push("请输入有效的合约代码，如 a2509, rb2509".to_string());
    } else if order.instrument_id.len() < 4 {
        issues.push("合约代码格式可能不正确".to_string());
        suggestions.push("合约代码通常为4-6位，如 a2509 (豆一2509)".to_string());
    }

    // 2. 检查价格
    if order.price <= 0.0 {
        issues.push("价格必须大于0".to_string());
        suggestions.push("请输入有效的价格".to_string());
    } else if order.price > 100000.0 {
        issues.push("价格可能过高".to_string());
        suggestions.push("请检查价格是否合理，是否在涨跌停板范围内".to_string());
    }

    // 3. 检查数量
    if order.volume <= 0 {
        issues.push("数量必须大于0".to_string());
        suggestions.push("请输入有效的数量".to_string());
    } else if order.volume > 1000 {
        issues.push("数量可能过大".to_string());
        suggestions.push("大量订单可能需要更多保证金，请检查账户资金".to_string());
    }

    // 4. 检查交易会话
    let session_exists = {
        let apis = TRADER_APIS.lock().unwrap();
        apis.contains_key(&session_id)
    };

    if !session_exists {
        issues.push("交易会话不存在".to_string());
        suggestions.push("请先创建交易API连接".to_string());
    }

    // 5. 检查登录状态
    let login_status = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&session_id).copied().unwrap_or(false)
    };

    if !login_status {
        issues.push("未登录交易系统".to_string());
        suggestions.push("请先完成交易登录".to_string());
    }

    // 6. 检查结算确认状态
    let settlement_confirmed = {
        let confirm_status = SETTLEMENT_CONFIRM_STATUS.lock().unwrap();
        confirm_status.get(&session_id).copied().unwrap_or(false)
    };

    if !settlement_confirmed {
        issues.push("未确认结算结果".to_string());
        suggestions.push("请先确认结算结果".to_string());
    }

    // 7. 常见的订单参数问题
    if order.direction != "0" && order.direction != "1" {
        issues.push("买卖方向参数错误".to_string());
        suggestions.push("买卖方向应为 '0'(买入) 或 '1'(卖出)".to_string());
    }

    if order.order_type != "1" && order.order_type != "2" {
        issues.push("订单类型参数错误".to_string());
        suggestions.push("订单类型应为 '1'(市价) 或 '2'(限价)".to_string());
    }

    analysis.insert("session_id".to_string(), serde_json::Value::String(session_id));
    analysis.insert("instrument_id".to_string(), serde_json::Value::String(order.instrument_id));
    analysis.insert("issues_found".to_string(), serde_json::Value::Number(serde_json::Number::from(issues.len())));
    analysis.insert("issues".to_string(), serde_json::Value::Array(
        issues.into_iter().map(serde_json::Value::String).collect()
    ));
    analysis.insert("suggestions".to_string(), serde_json::Value::Array(
        suggestions.into_iter().map(serde_json::Value::String).collect()
    ));

    // 添加系统状态信息
    let mut system_status = serde_json::Map::new();
    system_status.insert("session_exists".to_string(), serde_json::Value::Bool(session_exists));
    system_status.insert("login_status".to_string(), serde_json::Value::Bool(login_status));
    system_status.insert("settlement_confirmed".to_string(), serde_json::Value::Bool(settlement_confirmed));
    analysis.insert("system_status".to_string(), serde_json::Value::Object(system_status));

    ApiResponse {
        success: true,
        data: Some(serde_json::Value::Object(analysis)),
        error: None,
    }
}

// 检查订单提交的详细状态
#[command]
pub fn check_order_submission_status(session_id: String) -> ApiResponse<serde_json::Value> {
    println!("🔍 [DEBUG] check_order_submission_status called with session_id: {}", session_id);

    let mut status = serde_json::Map::new();

    // 1. 检查交易API连接状态
    let trader_connected = {
        let apis = TRADER_APIS.lock().unwrap();
        apis.contains_key(&session_id)
    };
    status.insert("trader_api_connected".to_string(), serde_json::Value::Bool(trader_connected));

    // 2. 检查登录状态
    let login_status = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&session_id).copied().unwrap_or(false)
    };
    status.insert("login_status".to_string(), serde_json::Value::Bool(login_status));

    // 3. 检查结算确认状态
    let settlement_confirmed = {
        let confirm_status = SETTLEMENT_CONFIRM_STATUS.lock().unwrap();
        confirm_status.get(&session_id).copied().unwrap_or(false)
    };
    status.insert("settlement_confirmed".to_string(), serde_json::Value::Bool(settlement_confirmed));

    // 4. 检查最近的订单结果
    let recent_orders = {
        let order_results = ORDER_INSERT_RESULTS.lock().unwrap();
        let mut orders = Vec::new();
        for (order_ref, (success, message)) in order_results.iter() {
            orders.push(serde_json::json!({
                "order_ref": order_ref,
                "success": success,
                "message": message
            }));
        }
        orders
    };
    let recent_orders_empty = recent_orders.is_empty();
    status.insert("recent_orders".to_string(), serde_json::Value::Array(recent_orders));

    // 5. 检查当前时间是否在交易时段
    let current_time = chrono::Local::now();
    let hour = current_time.hour();
    let minute = current_time.minute();
    let time_minutes = hour * 60 + minute;

    // 期货交易时间段 (简化版本)
    let is_trading_time =
        (time_minutes >= 9 * 60 && time_minutes <= 11 * 60 + 30) ||  // 09:00-11:30
        (time_minutes >= 13 * 60 + 30 && time_minutes <= 15 * 60) ||  // 13:30-15:00
        (time_minutes >= 21 * 60 && time_minutes <= 23 * 60);         // 21:00-23:00 (夜盘)

    status.insert("is_trading_time".to_string(), serde_json::Value::Bool(is_trading_time));
    status.insert("current_time".to_string(), serde_json::Value::String(current_time.format("%H:%M:%S").to_string()));

    // 6. 提供诊断建议
    let mut suggestions = Vec::new();

    if !trader_connected {
        suggestions.push("请先创建交易API连接");
    }
    if !login_status {
        suggestions.push("请完成交易登录");
    }
    if !settlement_confirmed {
        suggestions.push("请确认结算结果");
    }
    if !is_trading_time {
        suggestions.push("当前可能不在交易时间内，请确认交易时段");
    }
    if recent_orders_empty {
        suggestions.push("没有订单提交记录，可能存在网络连接问题");
    }

    status.insert("suggestions".to_string(), serde_json::Value::Array(
        suggestions.into_iter().map(|s| serde_json::Value::String(s.to_string())).collect()
    ));

    // 7. 整体状态评估
    let overall_ready = trader_connected && login_status && settlement_confirmed;
    status.insert("ready_for_trading".to_string(), serde_json::Value::Bool(overall_ready));

    ApiResponse {
        success: true,
        data: Some(serde_json::Value::Object(status)),
        error: None,
    }
}

// 检查结算确认状态
#[command]
pub fn check_settlement_confirm_status(session_id: String) -> ApiResponse<bool> {
    println!("🔍 [DEBUG] check_settlement_confirm_status called with session_id: {}", session_id);

    let confirm_status = {
        let confirm_status = SETTLEMENT_CONFIRM_STATUS.lock().unwrap();
        confirm_status.get(&session_id).copied().unwrap_or(false)
    };

    ApiResponse {
        success: true,
        data: Some(confirm_status),
        error: if confirm_status { None } else { Some("结算结果未确认".to_string()) },
    }
}

// 验证订单字段的有效性
fn validate_order_fields(order: &OrderRequest) -> Result<(), String> {
    // 验证合约代码
    if order.instrument_id.is_empty() {
        return Err("合约代码不能为空".to_string());
    }
    if order.instrument_id.len() > 30 {
        return Err("合约代码长度不能超过30个字符".to_string());
    }

    // 验证买卖方向
    if order.direction != "0" && order.direction != "1" {
        return Err("买卖方向必须是 '0'(买入) 或 '1'(卖出)".to_string());
    }

    // 验证价格
    if order.price <= 0.0 {
        return Err("价格必须大于0".to_string());
    }
    if order.price > 999999.99 {
        return Err("价格不能超过999999.99".to_string());
    }

    // 验证数量
    if order.volume <= 0 {
        return Err("数量必须大于0".to_string());
    }
    if order.volume > 1000000 {
        return Err("数量不能超过1000000".to_string());
    }

    // 验证订单类型
    if order.order_type != "1" && order.order_type != "2" {
        return Err("订单类型必须是 '1'(市价) 或 '2'(限价)".to_string());
    }

    // 验证开平标志
    if let Some(ref offset) = order.offset_flag {
        if !["0", "1", "3", "4"].contains(&offset.as_str()) {
            return Err("开平标志必须是 '0'(开仓), '1'(平仓), '3'(平今), '4'(平昨)".to_string());
        }
    }

    // 验证投机套保标志
    if let Some(ref hedge) = order.hedge_flag {
        if !["1", "2", "3"].contains(&hedge.as_str()) {
            return Err("投机套保标志必须是 '1'(投机), '2'(套利), '3'(套保)".to_string());
        }
    }

    Ok(())
}

// 验证交易会话是否存在
#[command]
pub fn validate_trader_session(session_id: String) -> ApiResponse<bool> {
    let apis = TRADER_APIS.lock().unwrap();
    let exists = apis.contains_key(&session_id);

    ApiResponse {
        success: exists,
        data: Some(exists),
        error: if exists { None } else { Some("Session not found".to_string()) },
    }
}

// 检查CTP连接状态和诊断信息
#[command]
pub fn check_ctp_connection_status(session_id: String) -> ApiResponse<serde_json::Value> {
    println!("🔍 [DEBUG] check_ctp_connection_status called with session_id: {}", session_id);

    let mut status_info = serde_json::Map::new();

    // 检查交易API是否存在
    let trader_exists = {
        let apis = TRADER_APIS.lock().unwrap();
        apis.contains_key(&session_id)
    };

    status_info.insert("trader_api_exists".to_string(), serde_json::Value::Bool(trader_exists));

    // 检查登录状态
    let login_status = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&session_id).copied().unwrap_or(false)
    };

    status_info.insert("login_status".to_string(), serde_json::Value::Bool(login_status));

    // 检查登录配置是否存在
    let config_exists = {
        let session_info = SESSION_LOGIN_INFO.lock().unwrap();
        session_info.contains_key(&session_id)
    };

    status_info.insert("config_exists".to_string(), serde_json::Value::Bool(config_exists));

    // 提供诊断建议
    let mut suggestions = Vec::new();

    if !trader_exists {
        suggestions.push("请先创建交易API".to_string());
    }

    if !login_status {
        suggestions.push("请完成交易登录".to_string());
    }

    if !config_exists {
        suggestions.push("请检查登录配置信息".to_string());
    }

    if trader_exists && !login_status {
        suggestions.push("建议检查网络连接和前置地址".to_string());
        suggestions.push("确认账户信息和密码正确".to_string());
    }

    status_info.insert("suggestions".to_string(), serde_json::Value::Array(
        suggestions.into_iter().map(serde_json::Value::String).collect()
    ));

    // 添加错误代码说明
    let mut error_codes = serde_json::Map::new();
    error_codes.insert("-1".to_string(), serde_json::Value::String("网络连接错误或API未正确连接".to_string()));
    error_codes.insert("-2".to_string(), serde_json::Value::String("未处理请求超过许可数".to_string()));
    error_codes.insert("-3".to_string(), serde_json::Value::String("每秒发送请求数超过许可数".to_string()));

    status_info.insert("error_codes".to_string(), serde_json::Value::Object(error_codes));

    ApiResponse {
        success: true,
        data: Some(serde_json::Value::Object(status_info)),
        error: None,
    }
}

// 获取系统临时目录的 CTP 缓存路径
fn get_ctp_cache_path(session_id: &str) -> Result<String, String> {
    let temp_dir = std::env::temp_dir();
    let ctp_cache_dir = temp_dir.join("ctp_cache").join(session_id);

    // 确保目录存在
    if let Err(e) = std::fs::create_dir_all(&ctp_cache_dir) {
        return Err(format!("Failed to create cache directory: {}", e));
    }

    Ok(ctp_cache_dir.to_string_lossy().to_string().replace("\\", "/"))
}

// 获取下一个请求ID
fn get_next_request_id() -> i32 {
    let mut counter = REQUEST_ID_COUNTER.lock().unwrap();
    let id = *counter;
    *counter += 1;
    id
}

// 获取下一个订单引用
fn get_next_order_ref() -> String {
    let mut counter = ORDER_REF_COUNTER.lock().unwrap();
    let ref_id = *counter;
    *counter += 1;
    format!("{}", ref_id)
}

// 设置全局App Handle
pub fn set_app_handle(app_handle: AppHandle) {
    let mut handle = APP_HANDLE.lock().unwrap();
    *handle = Some(app_handle);
    // App handle set successfully
}

// 安全地复制字符串到CTP字符数组
fn copy_str_to_ctp_array(src: &str, dst: &mut [i8]) {
    let src_bytes = src.as_bytes();
    let max_len = std::cmp::min(src_bytes.len(), dst.len() - 1);

    // 清零数组
    for i in 0..dst.len() {
        dst[i] = 0;
    }

    // 复制字符串
    for i in 0..max_len {
        dst[i] = src_bytes[i] as i8;
    }
}

// 安全的 MD API 创建函数
fn create_md_api_safe(
    session_id: &str,
    flow_path: &str,
    is_using_udp: bool,
    is_multicast: bool,
) -> Result<String, String> {
    // 1. 如果提供了相对路径，使用系统临时目录
    let actual_flow_path = if flow_path.starts_with("../temp/") || flow_path.starts_with("./") {
        get_ctp_cache_path(session_id)?
    } else {
        // 验证绝对路径
        if flow_path.is_empty() {
            return Err("Flow path cannot be empty".to_string());
        }
        flow_path.to_string()
    };

    // 2. 确保目录存在
    if let Err(e) = std::fs::create_dir_all(&actual_flow_path) {
        return Err(format!("Failed to create directory {}: {}", actual_flow_path, e));
    }

    // 3. 检查是否已存在相同的 session_id
    {
        let apis = MD_APIS.lock().map_err(|e| format!("Failed to lock MD_APIS: {}", e))?;
        if apis.contains_key(session_id) {
            return Err(format!("Session ID {} already exists", session_id));
        }
    }

    // 4. 创建 API 和 Stream（这是可能崩溃的地方）

    // 使用 std::panic::catch_unwind 捕获可能的 panic
    let api_result = std::panic::catch_unwind(|| {
        // 添加额外的安全检查
        if actual_flow_path.len() > 256 {
            panic!("Flow path too long: {}", actual_flow_path.len());
        }

        // 确保目录存在
        if let Some(parent) = std::path::Path::new(&actual_flow_path).parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                // Failed to create directory
            }
        }

        // 创建API和Stream
        let mut api = md_api::create_api(&actual_flow_path, is_using_udp, is_multicast);
        let (stream, spi_ptr) = ctp_trade_lib::md_api::create_spi();

        // 注册SPI到API
        api.register_spi(spi_ptr);

        (api, stream)
    });

    let (api, stream) = match api_result {
        Ok((api, stream)) => {
            (api, stream)
        },
        Err(panic_info) => {
            let error_msg = format!("CTP MD API creation panicked: {:?}", panic_info);
            // Error occurred during API creation
            return Err(error_msg);
        }
    };

    // 5. 存储 API 和 Stream
    {
        let mut apis = MD_APIS.lock().map_err(|e| format!("Failed to lock MD_APIS for storage: {}", e))?;
        apis.insert(session_id.to_string(), api);
    }

    {
        let mut streams = MD_STREAMS.lock().map_err(|e| format!("Failed to lock MD_STREAMS for storage: {}", e))?;
        streams.insert(session_id.to_string(), stream);
    }

    // 6. 启动Stream处理任务
    start_md_stream_processing(session_id.to_string());

    Ok(session_id.to_string())
}

// 安全释放 Trader API 资源
fn release_trader_api_safe(session_id: &str) -> Result<(), String> {
    let mut apis = TRADER_APIS.lock().map_err(|e| format!("Failed to lock TRADER_APIS: {}", e))?;

    if let Some(_api) = apis.remove(session_id) {
        // 清理相关状态
        {
            let mut login_status = TRADER_LOGIN_STATUS.lock().unwrap();
            login_status.remove(session_id);
        }

        {
            let mut streams = TRADER_STREAMS.lock().unwrap();
            streams.remove(session_id);
        }

        {
            let mut session_info = SESSION_LOGIN_INFO.lock().unwrap();
            session_info.remove(session_id);
        }

        // 安全地释放 CTP API 资源
        let release_result = std::panic::catch_unwind(|| {
            // 注意：CTP API 的 release 方法可能会导致崩溃
            // 这里我们先不调用 release，让 Rust 的 Drop trait 处理
            // _api.release();
        });

        match release_result {
            Ok(_) => {
                println!("✅ [CLEANUP] Trader API released for session: {}", session_id);
                Ok(())
            },
            Err(_) => {
                let error_msg = format!("Trader API release panicked for session: {}", session_id);
                println!("❌ [ERROR] {}", error_msg);
                Err(error_msg)
            }
        }
    } else {
        let error_msg = format!("Trader session ID {} not found", session_id);
        Err(error_msg)
    }
}

// 安全释放 MD API 资源
fn release_md_api_safe(session_id: &str) -> Result<(), String> {
    let mut apis = MD_APIS.lock().map_err(|e| format!("Failed to lock MD_APIS: {}", e))?;

    if let Some(_api) = apis.remove(session_id) {

        // 安全地释放 CTP API 资源
        let release_result = std::panic::catch_unwind(|| {
            // 注意：CTP API 的 release 方法可能会导致崩溃
            // 这里我们先不调用 release，让 Rust 的 Drop trait 处理
            // _api.release();
        });

        match release_result {
            Ok(_) => {
                Ok(())
            },
            Err(_) => {
                let error_msg = format!("MD API release panicked for session: {}", session_id);
                Err(error_msg)
            }
        }
    } else {
        let error_msg = format!("Session ID {} not found", session_id);
        Err(error_msg)
    }
}

// 基础 API 命令
#[command]
pub fn get_api_version() -> ApiResponse<String> {
    match ctp_get_api_version() {
        Some(version) => ApiResponse {
            success: true,
            data: Some(version),
            error: None,
        },
        None => ApiResponse {
            success: false,
            data: None,
            error: Some("Failed to get API version".to_string()),
        },
    }
}

#[command]
pub fn create_md_api(
    session_id: String,
    flow_path: String,
    is_using_udp: bool,
    is_multicast: bool,
) -> ApiResponse<String> {


    match create_md_api_safe(&session_id, &flow_path, is_using_udp, is_multicast) {
        Ok(session_id) => {
            ApiResponse {
                success: true,
                data: Some(session_id),
                error: None,
            }
        },
        Err(error) => {
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 释放交易API
#[command]
pub fn release_trader_api(session_id: String) -> ApiResponse<String> {
    println!("🔄 [CLEANUP] Releasing trader API for session: {}", session_id);

    match release_trader_api_safe(&session_id) {
        Ok(_) => {
            println!("✅ [CLEANUP] Trader API released successfully for session: {}", session_id);
            ApiResponse {
                success: true,
                data: Some(format!("Trader API released for session: {}", session_id)),
                error: None,
            }
        },
        Err(error) => {
            println!("❌ [ERROR] Failed to release trader API for session {}: {}", session_id, error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

#[command]
pub fn release_md_api(session_id: String) -> ApiResponse<String> {
    match release_md_api_safe(&session_id) {
        Ok(_) => {
            ApiResponse {
                success: true,
                data: Some(format!("MD API {} released", session_id)),
                error: None,
            }
        },
        Err(error) => {
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

#[command]
pub fn create_trader_api(
    session_id: String,
    flow_path: String,
    encrypt: bool,
) -> ApiResponse<String> {
    match std::panic::catch_unwind(|| {
        // 检查是否已存在相同的 session_id
        {
            let apis = TRADER_APIS.lock().unwrap();
            if apis.contains_key(&session_id) {
                return Err(format!("Trader session ID {} already exists", session_id));
            }
        }

        // 确保目录存在
        if let Err(e) = std::fs::create_dir_all(&flow_path) {
            return Err(format!("Failed to create directory {}: {}", flow_path, e));
        }

        // 创建API和Stream
        let mut api = trader_api::create_api(&flow_path, encrypt);
        let (stream, spi_ptr) = ctp_trade_lib::trader_api::create_spi();

        // 注册SPI到API
        api.register_spi(spi_ptr);

        // 存储API和Stream
        let mut apis = TRADER_APIS.lock().unwrap();
        apis.insert(session_id.clone(), api);

        let mut streams = TRADER_STREAMS.lock().unwrap();
        streams.insert(session_id.clone(), stream);

        // 初始化登录状态为未登录
        let mut login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.insert(session_id.clone(), false);

        // 启动Stream处理任务
        start_trader_stream_processing(session_id.clone());

        Ok(session_id)
    }) {
        Ok(Ok(session_id)) => ApiResponse {
            success: true,
            data: Some(session_id),
            error: None,
        },
        Ok(Err(error)) => ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        },
        Err(_) => ApiResponse {
            success: false,
            data: None,
            error: Some("Failed to create Trader API".to_string()),
        },
    }
}

// 启动Trader Stream处理任务
fn start_trader_stream_processing(session_id: String) {
    use ctp_trade_lib::trader_api::CThostFtdcTraderSpiOutput;

    tokio::spawn(async move {
        println!("🔄 [STREAM] Starting trader stream processing for session: {}", session_id);

        // 获取Stream的所有权
        let stream_opt = {
            let mut streams = TRADER_STREAMS.lock().unwrap();
            streams.remove(&session_id)
        };

        if let Some(mut stream) = stream_opt {
            // 添加超时和错误处理
            let mut error_count = 0;
            const MAX_ERRORS: usize = 10;

            while let Some(event) = stream.next().await {
                // 使用 catch_unwind 捕获可能的 panic
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    match event {
                        CThostFtdcTraderSpiOutput::OnRspQryInstrument(packet) => {
                            // println!("📊 [STREAM] Received OnRspQryInstrument callback");

                            if let Some(instrument) = &packet.p_instrument {
                                handle_ctp_instrument_callback(instrument, packet.b_is_last);
                            } else if packet.b_is_last {
                                // 即使没有合约数据，如果是最后一个包，也要标记完成
                                let mut query_complete = INSTRUMENTS_QUERY_COMPLETE.lock().unwrap();
                                *query_complete = true;
                                println!("✅ [STREAM] Instrument query completed (no data)");
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnFrontConnected(_) => {
                            println!("🔗 [STREAM] Trader front connected");
                        },
                        CThostFtdcTraderSpiOutput::OnFrontDisconnected(packet) => {
                            let reason_text = match packet.n_reason {
                                0x1001 => "网络读失败",
                                0x1002 => "网络写失败",
                                0x2001 => "接收心跳超时",
                                0x2002 => "发送心跳失败",
                                0x2003 => "收到错误报文",
                                _ => "未知错误"
                            };
                            println!("❌ [STREAM] Trader front disconnected, reason: {} ({})", packet.n_reason, reason_text);

                            // 更新登录状态为断开
                            {
                                let mut login_status = TRADER_LOGIN_STATUS.lock().unwrap();
                                login_status.insert(session_id.clone(), false);
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRspUserLogin(packet) => {
                            println!("🔐 [STREAM] Received login response");
                            if let Some(rsp_info) = &packet.p_rsp_info {
                                if rsp_info.ErrorID == 0 {
                                    println!("✅ [STREAM] Login successful");

                                    // 获取并保存FrontID和SessionID
                                    if let Some(rsp_user_login) = &packet.p_rsp_user_login {
                                        let front_id = rsp_user_login.FrontID;
                                        let session_id_num = rsp_user_login.SessionID;

                                        println!("🔑 [DEBUG] 登录获取到 FrontID: {}, SessionID: {}", front_id, session_id_num);

                                        // 保存当前会话的FrontID和SessionID
                                        {
                                            let mut front_session_map = ORDER_FRONT_SESSION_MAP.lock().unwrap();
                                            front_session_map.insert(format!("session_{}", session_id), (front_id, session_id_num));
                                        }
                                    }

                                    let mut login_status = TRADER_LOGIN_STATUS.lock().unwrap();
                                    login_status.insert(session_id.clone(), true);

                                    // 更新登录结果
                                    let mut login_results = LOGIN_RESULTS.lock().unwrap();
                                    login_results.insert(session_id.clone(), (true, "CTP登录成功".to_string()));
                                } else {
                                    println!("❌ [STREAM] Login failed: {}",
                                        ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg));

                                    // 更新登录结果
                                    let mut login_results = LOGIN_RESULTS.lock().unwrap();
                                    let error_msg = ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg);
                                    login_results.insert(session_id.clone(), (false, error_msg.to_string()));
                                }
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRspOrderInsert(packet) => {
                            println!("📋 [STREAM] Received order insert response");
                            if let Some(rsp_info) = &packet.p_rsp_info {
                                if rsp_info.ErrorID == 0 {
                                    println!("✅ [STREAM] Order insert successful");
                                    if let Some(input_order) = &packet.p_input_order {
                                        let order_ref = ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.OrderRef);
                                        let instrument_id = ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.InstrumentID);
                                        println!("📋 [STREAM] Order details - Ref: {}, Instrument: {}, Volume: {}, Price: {}",
                                            order_ref, instrument_id, input_order.VolumeTotalOriginal, input_order.LimitPrice);

                                        // 保存成功结果
                                        let mut order_results = ORDER_INSERT_RESULTS.lock().unwrap();
                                        order_results.insert(order_ref.trim_end_matches('\0').to_string(),
                                            (true, "订单插入成功".to_string()));
                                    }
                                } else {
                                    let error_msg = ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg);
                                    println!("❌ [STREAM] Order insert failed: {}", error_msg);

                                    // 保存失败结果
                                    if let Some(input_order) = &packet.p_input_order {
                                        let order_ref = ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.OrderRef);
                                        let mut order_results = ORDER_INSERT_RESULTS.lock().unwrap();
                                        order_results.insert(order_ref.trim_end_matches('\0').to_string(),
                                            (false, error_msg.to_string()));
                                    }
                                }
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRspOrderAction(packet) => {
                            println!("📋 [STREAM] Received order action response");
                            if let Some(rsp_info) = &packet.p_rsp_info {
                                if rsp_info.ErrorID == 0 {
                                    println!("✅ [STREAM] Order action successful");
                                    if let Some(input_order_action) = &packet.p_input_order_action {
                                        let order_ref = ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order_action.OrderRef);
                                        let instrument_id = ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order_action.InstrumentID);
                                        println!("📋 [STREAM] Cancel details - Ref: {}, Instrument: {}, Action: {}",
                                            order_ref, instrument_id, input_order_action.ActionFlag);
                                    }
                                } else {
                                    println!("❌ [STREAM] Order action failed: {}",
                                        ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg));
                                }
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRtnOrder(packet) => {
                            println!("📋 [STREAM] Received order status update");
                            if let Some(order) = &packet.p_order {
                                let order_ref = ctp_trade_lib::gb18030_cstr_to_str_i8(&order.OrderRef);
                                let instrument_id = ctp_trade_lib::gb18030_cstr_to_str_i8(&order.InstrumentID);
                                let order_status = order.OrderStatus as u8;

                                // 详细的订单状态说明
                                let status_desc = match order_status {
                                    48 => "全部成交", // '0'
                                    49 => "部分成交还在队列中", // '1'
                                    50 => "部分成交不在队列中", // '2'
                                    51 => "未成交还在队列中", // '3'
                                    52 => "未成交不在队列中", // '4'
                                    53 => "撤单", // '5'
                                    97 => "未知", // 'a'
                                    98 => "尚未触发", // 'b'
                                    99 => "已触发", // 'c'
                                    _ => "其他状态",
                                };

                                println!("📋 [STREAM] Order update - Ref: {}, Instrument: {}, Status: {} ({}), Volume: {}/{}, FrontID: {}, SessionID: {}",
                                    order_ref, instrument_id, order_status, status_desc, order.VolumeTraded, order.VolumeTotal, order.FrontID, order.SessionID);

                                // 保存订单的FrontID和SessionID，用于后续撤单
                                {
                                    let mut front_session_map = ORDER_FRONT_SESSION_MAP.lock().unwrap();
                                    front_session_map.insert(order_ref.to_string(), (order.FrontID, order.SessionID));
                                }

                                // 如果订单被拒绝或有错误，更新订单插入结果
                                if order_status == 52 { // 未成交不在队列中 - 通常表示被拒绝
                                    let mut order_results = ORDER_INSERT_RESULTS.lock().unwrap();
                                    let order_ref_clean = order_ref.trim_end_matches('\0').to_string();

                                    // 获取订单状态信息
                                    let status_msg = ctp_trade_lib::gb18030_cstr_to_str_i8(&order.StatusMsg);
                                    let error_msg = if status_msg.trim().is_empty() {
                                        format!("订单被拒绝 - 状态: {}", status_desc)
                                    } else {
                                        format!("订单被拒绝 - {}", status_msg)
                                    };

                                    order_results.insert(order_ref_clean, (false, error_msg));
                                    println!("❌ [STREAM] Order rejected - Ref: {}, Reason: {}", order_ref, status_msg);
                                }
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRtnTrade(packet) => {
                            println!("💰 [STREAM] Received trade notification");
                            if let Some(trade) = &packet.p_trade {
                                let order_ref = ctp_trade_lib::gb18030_cstr_to_str_i8(&trade.OrderRef);
                                let instrument_id = ctp_trade_lib::gb18030_cstr_to_str_i8(&trade.InstrumentID);
                                println!("💰 [STREAM] Trade executed - Ref: {}, Instrument: {}, Volume: {}, Price: {}",
                                    order_ref, instrument_id, trade.Volume, trade.Price);
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRspQryOrder(packet) => {
                            println!("🔍 [STREAM] Received order query response");
                            if let Some(rsp_info) = &packet.p_rsp_info {
                                if rsp_info.ErrorID == 0 {
                                    if let Some(order) = &packet.p_order {
                                        let order_ref = ctp_trade_lib::gb18030_cstr_to_str_i8(&order.OrderRef);
                                        let instrument_id = ctp_trade_lib::gb18030_cstr_to_str_i8(&order.InstrumentID);
                                        let order_status = order.OrderStatus as u8;

                                        // 只收集未成交的订单（状态为未知或未成交还在队列中）
                                        if order_status == 97 || order_status == 51 {
                                            let direction = if order.Direction == 48 { "买入".to_string() } else { "卖出".to_string() };
                                            let status_desc = match order_status {
                                                97 => "未知",
                                                51 => "未成交还在队列中",
                                                _ => "其他"
                                            };

                                            let order_info = OrderInfo {
                                                order_ref: order_ref.to_string(),
                                                instrument_id: instrument_id.to_string(),
                                                direction,
                                                price: order.LimitPrice,
                                                volume: order.VolumeTotalOriginal,
                                                volume_traded: order.VolumeTraded,
                                                order_status: status_desc.to_string(),
                                                front_id: order.FrontID,
                                                session_id: order.SessionID,
                                            };

                                            // 添加到查询结果中
                                            let mut queried_orders = QUERIED_ORDERS.lock().unwrap();
                                            for (_, orders) in queried_orders.iter_mut() {
                                                orders.push(order_info.clone());
                                            }

                                            println!("🔍 [STREAM] 找到未成交订单 - Ref: {}, Instrument: {}, Direction: {}, Status: {}",
                                                order_ref, instrument_id, order_info.direction, status_desc);
                                        }
                                    }

                                    if packet.b_is_last {
                                        println!("✅ [STREAM] 订单查询完成");
                                    }
                                } else {
                                    println!("❌ [STREAM] Order query failed: {}",
                                        ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg));
                                }
                            }
                        },
                        CThostFtdcTraderSpiOutput::OnRspSettlementInfoConfirm(packet) => {
                            println!("📋 [STREAM] Received settlement confirm response");
                            if let Some(rsp_info) = &packet.p_rsp_info {
                                if rsp_info.ErrorID == 0 {
                                    println!("✅ [STREAM] Settlement confirm successful");
                                    let mut confirm_status = SETTLEMENT_CONFIRM_STATUS.lock().unwrap();
                                    confirm_status.insert(session_id.clone(), true);

                                    // 更新结算确认结果
                                    let mut confirm_results = SETTLEMENT_CONFIRM_RESULTS.lock().unwrap();
                                    confirm_results.insert(session_id.clone(), (true, "结算结果确认成功".to_string()));
                                } else {
                                    let error_msg = ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg);
                                    println!("❌ [STREAM] Settlement confirm failed: {}", error_msg);

                                    // 更新结算确认结果
                                    let mut confirm_results = SETTLEMENT_CONFIRM_RESULTS.lock().unwrap();
                                    confirm_results.insert(session_id.clone(), (false, error_msg.to_string()));
                                }
                            }
                        },
                        _ => {
                            // 处理其他事件
                            // println!("📨 [STREAM] Received other event: {:?}", event);
                        }
                    }
                }));

                // 处理 panic 结果
                match result {
                    Ok(_) => {
                        // 重置错误计数
                        error_count = 0;
                    },
                    Err(_) => {
                        error_count += 1;
                        println!("❌ [STREAM] Event processing panicked for session: {} (error count: {})", session_id, error_count);

                        if error_count >= MAX_ERRORS {
                            println!("❌ [STREAM] Too many errors, stopping stream processing for session: {}", session_id);
                            break;
                        }

                        // 短暂延迟后继续
                        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                    }
                }
            }
        }

        println!("🔄 [STREAM] Trader stream processing ended for session: {}", session_id);
    });
}

// 启动MD Stream处理任务
fn start_md_stream_processing(session_id: String) {
    use ctp_trade_lib::md_api::CThostFtdcMdSpiOutput;

    tokio::spawn(async move {
        // Starting MD stream processing

        // 获取Stream的所有权
        let stream_opt = {
            let mut streams = MD_STREAMS.lock().unwrap();
            streams.remove(&session_id)
        };

        if let Some(mut stream) = stream_opt {
            // 添加超时和错误处理
            let mut error_count = 0;
            const MAX_ERRORS: usize = 10;

            while let Some(event) = stream.next().await {
                // 使用 catch_unwind 捕获可能的 panic
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    match event {
                        CThostFtdcMdSpiOutput::OnRtnDepthMarketData(packet) => {
                            if let Some(market_data) = &packet.p_depth_market_data {
                                handle_ctp_market_data_callback(market_data, &session_id);
                            }
                        },
                        CThostFtdcMdSpiOutput::OnFrontConnected(_) => {
                            // MD front connected
                        },
                        CThostFtdcMdSpiOutput::OnFrontDisconnected(packet) => {
                            // MD front disconnected, reason: packet.n_reason
                        },
                        CThostFtdcMdSpiOutput::OnRspUserLogin(packet) => {
                            if let Some(rsp_info) = &packet.p_rsp_info {
                                if rsp_info.ErrorID == 0 {
                                    let mut login_status = MD_LOGIN_STATUS.lock().unwrap();
                                    login_status.insert(session_id.clone(), true);

                                    // 更新登录结果
                                    let mut login_results = LOGIN_RESULTS.lock().unwrap();
                                    login_results.insert(session_id.clone(), (true, "CTP行情登录成功".to_string()));
                                } else {
                                    // 更新登录结果
                                    let mut login_results = LOGIN_RESULTS.lock().unwrap();
                                    let error_msg = ctp_trade_lib::gb18030_cstr_to_str_i8(&rsp_info.ErrorMsg);
                                    login_results.insert(session_id.clone(), (false, error_msg.to_string()));
                                }
                            }
                        },
                        _ => {
                            // 处理其他事件
                            // println!("📨 [MD_STREAM] Received other event: {:?}", event);
                        }
                    }
                }));

                // 处理 panic 结果
                match result {
                    Ok(_) => {
                        // 重置错误计数
                        error_count = 0;
                    },
                    Err(_) => {
                        error_count += 1;

                        if error_count >= MAX_ERRORS {
                            break;
                        }

                        // 短暂延迟后继续
                        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                    }
                }
            }
        }

        // MD stream processing ended
    });
}

// 处理CTP合约查询回调
fn handle_ctp_instrument_callback(instrument: &ctp_trade_lib::CThostFtdcInstrumentField, is_last: bool) {
    // 将CTP合约数据转换为我们的InstrumentInfo格式
    let instrument_info = InstrumentInfo {
        instrument_id: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.InstrumentID).trim_end_matches('\0').to_string(),
        exchange_id: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.ExchangeID).trim_end_matches('\0').to_string(),
        instrument_name: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.InstrumentName).to_string(),
        exchange_inst_id: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.ExchangeInstID).trim_end_matches('\0').to_string(),
        product_id: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.ProductID).trim_end_matches('\0').to_string(),
        product_class: format!("{}", instrument.ProductClass as u8),
        delivery_year: instrument.DeliveryYear,
        delivery_month: instrument.DeliveryMonth,
        max_market_order_volume: instrument.MaxMarketOrderVolume,
        min_market_order_volume: instrument.MinMarketOrderVolume,
        max_limit_order_volume: instrument.MaxLimitOrderVolume,
        min_limit_order_volume: instrument.MinLimitOrderVolume,
        volume_multiple: instrument.VolumeMultiple,
        price_tick: instrument.PriceTick,
        create_date: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.CreateDate).trim_end_matches('\0').to_string(),
        open_date: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.OpenDate).trim_end_matches('\0').to_string(),
        expire_date: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.ExpireDate).trim_end_matches('\0').to_string(),
        start_deliv_date: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.StartDelivDate).trim_end_matches('\0').to_string(),
        end_deliv_date: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.EndDelivDate).trim_end_matches('\0').to_string(),
        inst_life_phase: format!("{}", instrument.InstLifePhase as u8),
        is_trading: instrument.IsTrading,
        position_type: format!("{}", instrument.PositionType as u8),
        position_date_type: format!("{}", instrument.PositionDateType as u8),
        long_margin_ratio: instrument.LongMarginRatio,
        short_margin_ratio: instrument.ShortMarginRatio,
        max_margin_side_algorithm: format!("{}", instrument.MaxMarginSideAlgorithm as u8),
        underlying_inst_id: ctp_trade_lib::gb18030_cstr_to_str_i8(&instrument.UnderlyingInstrID).trim_end_matches('\0').to_string(),
        strike_price: instrument.StrikePrice,
        options_type: format!("{}", instrument.OptionsType as u8),
        underlying_multiple: instrument.UnderlyingMultiple,
        combination_type: format!("{}", instrument.CombinationType as u8),
    };

    // 添加到全局合约数据中
    {
        let mut instruments_data = CTP_INSTRUMENTS_DATA.lock().unwrap();
        instruments_data.push(instrument_info);

        // Progress tracking for instrument data
    }

    // 如果是最后一个包，标记查询完成
    if is_last {
        let mut query_complete = INSTRUMENTS_QUERY_COMPLETE.lock().unwrap();
        *query_complete = true;

        let instruments_count = {
            let instruments_data = CTP_INSTRUMENTS_DATA.lock().unwrap();
            instruments_data.len()
        };

        // Instrument query completed
    }
}

// 处理CTP行情数据回调
fn handle_ctp_market_data_callback(market_data: &ctp_trade_lib::CThostFtdcDepthMarketDataField, session_id: &str) {
    // 将CTP行情数据转换为我们的MarketDataInfo格式
    let instrument_id = ctp_trade_lib::gb18030_cstr_to_str_i8(&market_data.InstrumentID).trim_end_matches('\0').to_string();

    // 创建行情数据结构
    let market_data_info = serde_json::json!({
        "instrument_id": instrument_id,
        "last_price": if market_data.LastPrice != f64::MAX { market_data.LastPrice } else { 0.0 },
        "volume": market_data.Volume,
        "turnover": market_data.Turnover,
        "open_interest": market_data.OpenInterest,
        "pre_close_price": if market_data.PreClosePrice != f64::MAX { market_data.PreClosePrice } else { 0.0 },
        "pre_settlement_price": if market_data.PreSettlementPrice != f64::MAX { market_data.PreSettlementPrice } else { 0.0 },
        "pre_open_interest": market_data.PreOpenInterest,
        "open_price": if market_data.OpenPrice != f64::MAX { market_data.OpenPrice } else { 0.0 },
        "highest_price": if market_data.HighestPrice != f64::MAX { market_data.HighestPrice } else { 0.0 },
        "lowest_price": if market_data.LowestPrice != f64::MAX { market_data.LowestPrice } else { 0.0 },
        "upper_limit_price": if market_data.UpperLimitPrice != f64::MAX { market_data.UpperLimitPrice } else { 0.0 },
        "lower_limit_price": if market_data.LowerLimitPrice != f64::MAX { market_data.LowerLimitPrice } else { 0.0 },
        "settlement_price": if market_data.SettlementPrice != f64::MAX { market_data.SettlementPrice } else { 0.0 },
        "currency_id": "CNY".to_string(), // Default currency for Chinese futures market
        "bid_price1": if market_data.BidPrice1 != f64::MAX { market_data.BidPrice1 } else { 0.0 },
        "bid_volume1": market_data.BidVolume1,
        "ask_price1": if market_data.AskPrice1 != f64::MAX { market_data.AskPrice1 } else { 0.0 },
        "ask_volume1": market_data.AskVolume1,
        "update_time": ctp_trade_lib::gb18030_cstr_to_str_i8(&market_data.UpdateTime).trim_end_matches('\0').to_string(),
        "update_millisec": market_data.UpdateMillisec,
        "action_day": ctp_trade_lib::gb18030_cstr_to_str_i8(&market_data.ActionDay).trim_end_matches('\0').to_string(),
    });

    // Market data processed for instrument

    // 发送行情数据事件到前端
    let app_handle_opt = {
        let handle = APP_HANDLE.lock().unwrap();
        handle.clone()
    };

    if let Some(app_handle) = app_handle_opt {
        // 发送market_data事件到前端
        let _ = app_handle.emit("market_data", &market_data_info);
    }
}

// 验证登录凭据的基本有效性
fn validate_login_credentials(config: &CtpAccountConfig) -> Result<(), String> {
    if config.broker_id.is_empty() {
        return Err("经纪公司代码不能为空".to_string());
    }
    if config.account.is_empty() {
        return Err("账户不能为空".to_string());
    }
    if config.password.is_empty() {
        return Err("密码不能为空".to_string());
    }
    if config.md_front.is_empty() {
        return Err("行情前置地址不能为空".to_string());
    }
    if config.trade_front.is_empty() {
        return Err("交易前置地址不能为空".to_string());
    }

    // 基本格式验证
    if !config.md_front.starts_with("tcp://") {
        return Err("行情前置地址格式错误，应以tcp://开头".to_string());
    }
    if !config.trade_front.starts_with("tcp://") {
        return Err("交易前置地址格式错误，应以tcp://开头".to_string());
    }

    Ok(())
}

// 模拟CTP登录验证（简化版本）
fn simulate_ctp_login_validation(config: &CtpAccountConfig) -> Result<String, String> {
    // 模拟一些常见的CTP登录验证规则

    // 1. 检查经纪公司代码格式
    if config.broker_id.len() != 4 || !config.broker_id.chars().all(|c| c.is_ascii_digit()) {
        return Err("经纪公司代码格式错误，应为4位数字".to_string());
    }

    // 2. 检查账户格式
    if config.account.len() < 6 || config.account.len() > 15 {
        return Err("账户长度应在6-15位之间".to_string());
    }

    // 3. 检查密码强度
    if config.password.len() < 6 {
        return Err("密码长度不能少于6位".to_string());
    }

    // 4. 模拟一些已知的测试账户
    let valid_test_accounts = vec![
        ("9999", "183136", "cb@12345678"), // SimNow模拟账户
        ("9999", "183137", "cb@12345678"),
        ("9999", "183138", "cb@12345678"),
    ];

    for (broker, account, password) in valid_test_accounts {
        if config.broker_id == broker && config.account == account && config.password == password {
            return Ok(format!("登录成功 - 经纪商: {}, 账户: {}", broker, account));
        }
    }

    // 5. 对于其他账户，进行基本格式验证后拒绝
    Err(format!("登录失败 - 账户验证失败，请检查经纪商代码、账户和密码是否正确"))
}

// 等待登录结果（等待真实CTP回调）
fn wait_for_login_result(session_id: &str, timeout_seconds: u64) -> Result<String, String> {

    let start_time = std::time::Instant::now();
    let timeout_duration = std::time::Duration::from_secs(timeout_seconds);

    loop {
        // 检查是否超时
        if start_time.elapsed() > timeout_duration {
            // 超时后使用模拟验证作为后备

            let config = {
                let session_info = SESSION_LOGIN_INFO.lock().unwrap();
                session_info.get(session_id).cloned()
            };

            if let Some(config) = config {
                return simulate_ctp_login_validation(&config);
            } else {
                return Err("会话信息未找到".to_string());
            }
        }

        // 检查登录结果（来自Stream回调）
        {
            let login_results = LOGIN_RESULTS.lock().unwrap();
            if let Some((success, message)) = login_results.get(session_id) {
                if *success {
                    return Ok(message.clone());
                } else {
                    return Err(message.clone());
                }
            }
        }

        // 等待100ms后重试
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}



// 等待结算确认结果（等待真实CTP回调）
fn wait_for_settlement_confirm_result(session_id: &str, timeout_seconds: u64) -> Result<String, String> {
    println!("🔍 [DEBUG] Waiting for settlement confirm result for session_id: {}", session_id);

    let start_time = std::time::Instant::now();
    let timeout_duration = std::time::Duration::from_secs(timeout_seconds);

    loop {
        // 检查是否超时
        if start_time.elapsed() > timeout_duration {
            return Err(format!("等待结算确认结果超时 ({}秒)", timeout_seconds));
        }

        // 检查结算确认结果（来自Stream回调）
        {
            let confirm_results = SETTLEMENT_CONFIRM_RESULTS.lock().unwrap();
            if let Some((success, message)) = confirm_results.get(session_id) {
                if *success {
                    return Ok(message.clone());
                } else {
                    return Err(message.clone());
                }
            }
        }

        // 等待100ms后重试
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}





// 行情 API 命令
#[command]
pub fn md_login(
    session_id: String,
    config: CtpAccountConfig,
) -> ApiResponse<String> {
    // 验证登录凭据
    if let Err(validation_error) = validate_login_credentials(&config) {
        return ApiResponse {
            success: false,
            data: None,
            error: Some(validation_error),
        };
    }

    // 保存会话登录信息
    {
        let mut session_info = SESSION_LOGIN_INFO.lock().unwrap();
        session_info.insert(session_id.clone(), config.clone());
    }

    // 清除之前的登录结果
    {
        let mut login_results = LOGIN_RESULTS.lock().unwrap();
        login_results.remove(&session_id);
    }

    match std::panic::catch_unwind(|| {
        let mut apis = MD_APIS.lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            // 注册前置服务器
            let md_front = std::ffi::CString::new(config.md_front.clone()).unwrap();
            api.register_front(md_front);

            // 初始化API
            api.init();

            // 等待连接建立
            std::thread::sleep(std::time::Duration::from_millis(2000));

            // 构造登录请求
            let mut login_req = ctp_trade_lib::CThostFtdcReqUserLoginField::default();

            // 设置经纪公司代码
            let broker_id_cstr = std::ffi::CString::new(config.broker_id.clone()).unwrap();
            let broker_id_bytes = broker_id_cstr.as_bytes_with_nul();
            let broker_len = std::cmp::min(broker_id_bytes.len() - 1, 10); // -1 to exclude null terminator
            unsafe {
                std::ptr::copy_nonoverlapping(
                    broker_id_bytes.as_ptr() as *const i8,
                    login_req.BrokerID.as_mut_ptr(),
                    broker_len
                );
            }

            // 设置用户代码
            let user_id_cstr = std::ffi::CString::new(config.account.clone()).unwrap();
            let user_id_bytes = user_id_cstr.as_bytes_with_nul();
            let user_len = std::cmp::min(user_id_bytes.len() - 1, 15);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    user_id_bytes.as_ptr() as *const i8,
                    login_req.UserID.as_mut_ptr(),
                    user_len
                );
            }

            // 设置密码
            let password_cstr = std::ffi::CString::new(config.password.clone()).unwrap();
            let password_bytes = password_cstr.as_bytes_with_nul();
            let pwd_len = std::cmp::min(password_bytes.len() - 1, 40);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    password_bytes.as_ptr() as *const i8,
                    login_req.Password.as_mut_ptr(),
                    pwd_len
                );
            }

            // 发送登录请求 - 添加额外的安全检查
            let login_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                api.req_user_login(&mut login_req, 1)
            }));

            match login_result {
                Ok(result) if result == 0 => {

                    // 等待登录结果
                    match wait_for_login_result(&session_id, 10) {
                        Ok(success_msg) => {
                            // 设置登录状态
                            let mut md_status = MD_LOGIN_STATUS.lock().unwrap();
                            md_status.insert(session_id.clone(), true);
                            Ok(success_msg)
                        },
                        Err(error_msg) => {
                            Err(error_msg)
                        }
                    }
                },
                Ok(result) => {
                    Err(format!("MD login request failed with code: {}", result))
                },
                Err(_) => {
                    Err("MD login request panicked - possible memory corruption".to_string())
                }
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(message)) => {
            ApiResponse {
                success: true,
                data: Some(message),
                error: None,
            }
        },
        Ok(Err(error)) => {
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "MD login panicked".to_string();
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

#[command]
pub fn subscribe_market_data(
    session_id: String,
    request: MarketDataRequest,
) -> ApiResponse<String> {

    match std::panic::catch_unwind(|| {
        let mut apis = MD_APIS.lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            // 转换合约代码为CString
            let instruments: Vec<std::ffi::CString> = request.instrument_ids
                .iter()
                .map(|id| std::ffi::CString::new(id.as_str()).unwrap())
                .collect();

            let count = instruments.len() as std::os::raw::c_int;

            // 订阅行情
            let result = api.subscribe_market_data(instruments, count);

            if result == 0 {
                Ok(format!("Successfully subscribed to {} instruments", request.instrument_ids.len()))
            } else {
                Err(format!("Failed to subscribe market data, error code: {}", result))
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(message)) => {
            ApiResponse {
                success: true,
                data: Some(message),
                error: None,
            }
        },
        Ok(Err(error)) => {
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Subscribe market data panicked".to_string();
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

#[command]
pub fn unsubscribe_market_data(
    _session_id: String,
    request: MarketDataRequest,
) -> ApiResponse<String> {
    // 实现取消订阅行情数据的逻辑
    ApiResponse {
        success: true,
        data: Some(format!("Unsubscribed from {} instruments", request.instrument_ids.len())),
        error: None,
    }
}

// 结算确认命令
#[command]
pub fn settlement_info_confirm(
    session_id: String,
) -> ApiResponse<String> {
    println!("📋 [DEBUG] settlement_info_confirm called with session_id: {}", session_id);

    // 检查交易API是否存在
    let trader_exists = {
        let apis = TRADER_APIS.lock().unwrap();
        apis.contains_key(&session_id)
    };

    if !trader_exists {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("交易API会话不存在，请先创建交易API".to_string()),
        };
    }

    // 检查是否已登录
    let login_status = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&session_id).copied().unwrap_or(false)
    };

    if !login_status {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("请先完成交易登录".to_string()),
        };
    }

    // 获取登录配置信息
    let account_config = {
        let session_info = SESSION_LOGIN_INFO.lock().unwrap();
        session_info.get(&session_id).cloned()
    };

    let account_config = match account_config {
        Some(config) => config,
        None => {
            return ApiResponse {
                success: false,
                data: None,
                error: Some("未找到登录配置信息".to_string()),
            };
        }
    };

    match std::panic::catch_unwind(|| {
        let mut apis = TRADER_APIS.lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            // 清除之前的结算确认结果
            {
                let mut confirm_results = SETTLEMENT_CONFIRM_RESULTS.lock().unwrap();
                confirm_results.remove(&session_id);
            }

            // 构造结算确认请求
            let mut settlement_confirm = ctp_trade_lib::CThostFtdcSettlementInfoConfirmField::default();

            // 设置经纪公司代码
            copy_str_to_ctp_array(&account_config.broker_id, &mut settlement_confirm.BrokerID);

            // 设置投资者代码
            copy_str_to_ctp_array(&account_config.account, &mut settlement_confirm.InvestorID);

            // 设置账户代码
            copy_str_to_ctp_array(&account_config.account, &mut settlement_confirm.AccountID);

            // 设置币种代码（默认人民币）
            copy_str_to_ctp_array("CNY", &mut settlement_confirm.CurrencyID);

            // 获取当前日期和时间
            let now = chrono::Local::now();
            let confirm_date = now.format("%Y%m%d").to_string();
            let confirm_time = now.format("%H:%M:%S").to_string();

            copy_str_to_ctp_array(&confirm_date, &mut settlement_confirm.ConfirmDate);
            copy_str_to_ctp_array(&confirm_time, &mut settlement_confirm.ConfirmTime);

            // 获取请求ID
            let request_id = get_next_request_id();

            println!("📋 [DEBUG] Settlement confirm details:");
            println!("  - BrokerID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&settlement_confirm.BrokerID));
            println!("  - InvestorID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&settlement_confirm.InvestorID));
            println!("  - AccountID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&settlement_confirm.AccountID));
            println!("  - CurrencyID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&settlement_confirm.CurrencyID));
            println!("  - ConfirmDate: {}", confirm_date);
            println!("  - ConfirmTime: {}", confirm_time);
            println!("  - RequestID: {}", request_id);

            // 调用CTP API确认结算信息
            let result = api.req_settlement_info_confirm(&mut settlement_confirm, request_id);

            if result == 0 {
                println!("✅ [DEBUG] ReqSettlementInfoConfirm request sent successfully, waiting for CTP response...");

                // 等待真实的CTP响应
                match wait_for_settlement_confirm_result(&session_id, 10) {
                    Ok(success_msg) => {
                        println!("✅ [DEBUG] Settlement confirm confirmed by CTP: {}", success_msg);
                        Ok(success_msg)
                    },
                    Err(error_msg) => {
                        println!("❌ [DEBUG] Settlement confirm rejected by CTP: {}", error_msg);
                        Err(format!("CTP拒绝结算确认: {}", error_msg))
                    }
                }
            } else {
                println!("❌ [DEBUG] ReqSettlementInfoConfirm failed with code: {}", result);
                Err(format!("提交结算确认失败，错误代码: {}", result))
            }
        } else {
            Err("未找到交易API会话".to_string())
        }
    }) {
        Ok(Ok(message)) => ApiResponse {
            success: true,
            data: Some(message),
            error: None,
        },
        Ok(Err(error)) => ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        },
        Err(_) => ApiResponse {
            success: false,
            data: None,
            error: Some("结算确认过程中发生异常".to_string()),
        },
    }
}

// 交易 API 命令
#[command]
pub fn trader_login(
    session_id: String,
    config: CtpAccountConfig,
) -> ApiResponse<String> {
    println!("🔍 [DEBUG] trader_login called with session_id: {}", session_id);

    // 验证登录凭据
    if let Err(validation_error) = validate_login_credentials(&config) {
        println!("❌ [ERROR] Trader login validation failed: {}", validation_error);
        return ApiResponse {
            success: false,
            data: None,
            error: Some(validation_error),
        };
    }

    // 保存会话登录信息（在验证前保存，确保wait_for_login_result能找到）
    {
        let mut session_info = SESSION_LOGIN_INFO.lock().unwrap();
        session_info.insert(session_id.clone(), config.clone());
    }

    // 清除之前的登录结果
    {
        let mut login_results = LOGIN_RESULTS.lock().unwrap();
        login_results.remove(&session_id);
    }

    match std::panic::catch_unwind(|| {
        let mut apis = TRADER_APIS.lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 注册前置服务器
            let trade_front = std::ffi::CString::new(config.trade_front.clone()).unwrap();
            api.register_front(trade_front);
            println!("✅ [DEBUG] Registered trade front: {}", config.trade_front);

            // 初始化API
            api.init();
            println!("✅ [DEBUG] Trader API initialized");

            // 会话信息已在函数开始时保存

            // 等待连接建立
            std::thread::sleep(std::time::Duration::from_millis(2000));

            // 构造登录请求
            let mut login_req = ctp_trade_lib::CThostFtdcReqUserLoginField::default();

            // 设置经纪公司代码
            let broker_id_cstr = std::ffi::CString::new(config.broker_id.clone()).unwrap();
            let broker_id_bytes = broker_id_cstr.as_bytes_with_nul();
            let broker_len = std::cmp::min(broker_id_bytes.len() - 1, 10);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    broker_id_bytes.as_ptr() as *const i8,
                    login_req.BrokerID.as_mut_ptr(),
                    broker_len
                );
            }

            // 设置用户代码
            let user_id_cstr = std::ffi::CString::new(config.account.clone()).unwrap();
            let user_id_bytes = user_id_cstr.as_bytes_with_nul();
            let user_len = std::cmp::min(user_id_bytes.len() - 1, 15);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    user_id_bytes.as_ptr() as *const i8,
                    login_req.UserID.as_mut_ptr(),
                    user_len
                );
            }

            // 设置密码
            let password_cstr = std::ffi::CString::new(config.password.clone()).unwrap();
            let password_bytes = password_cstr.as_bytes_with_nul();
            let pwd_len = std::cmp::min(password_bytes.len() - 1, 40);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    password_bytes.as_ptr() as *const i8,
                    login_req.Password.as_mut_ptr(),
                    pwd_len
                );
            }

            // 设置用户产品信息
            let product_info_cstr = std::ffi::CString::new(config.user_product_info.clone()).unwrap();
            let product_info_bytes = product_info_cstr.as_bytes_with_nul();
            let product_len = std::cmp::min(product_info_bytes.len() - 1, 10);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    product_info_bytes.as_ptr() as *const i8,
                    login_req.UserProductInfo.as_mut_ptr(),
                    product_len
                );
            }

            println!("🔐 [DEBUG] Attempting Trader login with broker: {}, user: {}", config.broker_id, config.account);

            // 发送登录请求
            let login_result = api.req_user_login(&mut login_req, 1);

            if login_result == 0 {
                println!("✅ [DEBUG] Trader login request sent successfully, waiting for response...");

                // 等待登录结果
                match wait_for_login_result(&session_id, 15) {
                    Ok(success_msg) => {
                        // 设置登录状态
                        let mut trader_status = TRADER_LOGIN_STATUS.lock().unwrap();
                        trader_status.insert(session_id.clone(), true);
                        Ok(success_msg)
                    },
                    Err(error_msg) => {
                        Err(error_msg)
                    }
                }
            } else {
                Err(format!("Trader login request failed with code: {}", login_result))
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(message)) => {
            println!("✅ [SUCCESS] {}", message);
            ApiResponse {
                success: true,
                data: Some(message),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Trader login failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Trader login panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 强制设置交易登录状态（用于调试和测试）
#[command]
pub fn force_set_trader_login_status(
    session_id: String,
    status: bool,
) -> ApiResponse<String> {
    println!("🔍 [DEBUG] force_set_trader_login_status called with session_id: {}, status: {}", session_id, status);

    let apis = TRADER_APIS.lock().unwrap();
    if !apis.contains_key(&session_id) {
        return ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Session ID {} not found", session_id)),
        };
    }
    drop(apis);

    let mut login_status = TRADER_LOGIN_STATUS.lock().unwrap();
    login_status.insert(session_id.clone(), status);
    drop(login_status);

    let message = if status {
        format!("交易登录状态已设置为：已登录 (session: {})", session_id)
    } else {
        format!("交易登录状态已设置为：未登录 (session: {})", session_id)
    };

    println!("✅ [SUCCESS] {}", message);
    ApiResponse {
        success: true,
        data: Some(message),
        error: None,
    }
}

#[command]
pub fn insert_order(
    session_id: String,
    order: OrderRequest,
) -> ApiResponse<String> {
    println!("🔍 [DEBUG] insert_order called with session_id: {}, order: {:?}", session_id, order);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = TRADER_APIS.lock().unwrap();
        let login_info = SESSION_LOGIN_INFO.lock().unwrap();

        if let (Some(api), Some(account_config)) = (apis.get_mut(&session_id), login_info.get(&session_id)) {
            println!("✅ [DEBUG] Found Trader API and login info for session: {}", session_id);

            // 验证订单参数
            if let Err(validation_error) = validate_order_fields(&order) {
                println!("❌ [DEBUG] Order validation failed: {}", validation_error);
                return Err(validation_error);
            }
            println!("✅ [DEBUG] Order validation passed");

            // 检查结算确认状态
            let settlement_confirmed = {
                let confirm_status = SETTLEMENT_CONFIRM_STATUS.lock().unwrap();
                confirm_status.get(&session_id).copied().unwrap_or(false)
            };

            if !settlement_confirmed {
                println!("❌ [DEBUG] Settlement not confirmed for session: {}", session_id);
                return Err("结算结果未确认，请先进行结算确认后再进行交易操作".to_string());
            }
            println!("✅ [DEBUG] Settlement confirmed");

            // 引入CTP相关类型
            use ctp_trade_lib::*;

            // 创建输入报单结构
            let mut input_order = CThostFtdcInputOrderField::default();

            // 填充基本信息
            copy_str_to_ctp_array(&account_config.broker_id, &mut input_order.BrokerID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order.InvestorID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order.UserID);
            copy_str_to_ctp_array(&order.instrument_id, &mut input_order.InstrumentID);

            // 设置订单引用
            let order_ref = get_next_order_ref();
            copy_str_to_ctp_array(&order_ref, &mut input_order.OrderRef);

            // 设置买卖方向
            input_order.Direction = if order.direction == "0" {
                THOST_FTDC_D_Buy as i8
            } else {
                THOST_FTDC_D_Sell as i8
            };

            // 设置价格和数量
            input_order.LimitPrice = order.price;
            input_order.VolumeTotalOriginal = order.volume;

            // 设置报单价格条件
            input_order.OrderPriceType = match order.order_type.as_str() {
                "1" => THOST_FTDC_OPT_AnyPrice as i8,     // 市价单
                "2" => THOST_FTDC_OPT_LimitPrice as i8,   // 限价单
                _ => THOST_FTDC_OPT_LimitPrice as i8      // 默认限价单
            };

            // 设置开平标志
            input_order.CombOffsetFlag[0] = match order.offset_flag.as_deref().unwrap_or("0") {
                "0" => THOST_FTDC_OF_Open as i8,          // 开仓
                "1" => THOST_FTDC_OF_Close as i8,         // 平仓
                "3" => THOST_FTDC_OF_CloseToday as i8,    // 平今
                "4" => THOST_FTDC_OF_CloseYesterday as i8, // 平昨
                _ => THOST_FTDC_OF_Open as i8             // 默认开仓
            };

            // 设置投机套保标志
            input_order.CombHedgeFlag[0] = match order.hedge_flag.as_deref().unwrap_or("1") {
                "1" => THOST_FTDC_HF_Speculation as i8,   // 投机
                "2" => THOST_FTDC_HF_Arbitrage as i8,     // 套利
                "3" => THOST_FTDC_HF_Hedge as i8,         // 套保
                _ => THOST_FTDC_HF_Speculation as i8      // 默认投机
            };

            // 设置有效期类型
            input_order.TimeCondition = match order.time_condition.as_deref().unwrap_or("3") {
                "1" => THOST_FTDC_TC_IOC as i8,           // 立即完成，否则撤销
                "2" => THOST_FTDC_TC_GFS as i8,           // 本节有效
                "3" => THOST_FTDC_TC_GFD as i8,           // 当日有效
                "4" => THOST_FTDC_TC_GTD as i8,           // 指定日期前有效
                "5" => THOST_FTDC_TC_GTC as i8,           // 撤销前有效
                _ => THOST_FTDC_TC_IOC as i8              // 默认当日有效
            };

            // 设置成交量类型
            input_order.VolumeCondition = match order.volume_condition.as_deref().unwrap_or("1") {
                "1" => THOST_FTDC_VC_AV as i8,            // 任何数量
                "2" => THOST_FTDC_VC_MV as i8,            // 最小数量
                "3" => THOST_FTDC_VC_CV as i8,            // 全部数量
                _ => THOST_FTDC_VC_AV as i8               // 默认任何数量
            };

            // 设置触发条件 (默认立即)
            input_order.ContingentCondition = THOST_FTDC_CC_Immediately as i8;

            // 设置最小成交量
            input_order.MinVolume = 1;

            // 设置强平原因 (非强平)
            input_order.ForceCloseReason = THOST_FTDC_FCC_NotForceClose as i8;

            // 设置自动挂起标志
            input_order.IsAutoSuspend = 0; // 不自动挂起

            // 设置用户强评标志
            input_order.UserForceClose = 0; // 非用户强平

            // 设置互换单标志
            input_order.IsSwapOrder = 0; // 非互换单

            // 获取请求ID
            let request_id = get_next_request_id();

            // 设置请求编号（重要：CTP要求这个字段）
            input_order.RequestID = request_id;

            // 设置业务单元（可选，但建议设置为空）
            // input_order.BusinessUnit 保持默认值（全零）

            // 设置GTD日期（当日有效时可以为空）
            // input_order.GTDDate 保持默认值

            // 设置交易所代码（根据合约代码推断）
            // 改进的交易所识别逻辑
            let exchange_id = if order.instrument_id.len() >= 2 {
                let prefix = order.instrument_id.chars().take(2).collect::<String>().to_lowercase();
                match prefix.as_str() {
                    // 上期所 (SHFE)
                    "rb" | "hc" | "ss" | "wr" | "fu" | "bu" | "ru" | "sp" | "au" | "ag" |
                    "cu" | "al" | "zn" | "pb" | "ni" | "sn" | "sc" | "lu" | "bc" | "nr" => "SHFE",

                    // 中金所 (CFFEX) - 通常是大写字母开头
                    _ if order.instrument_id.starts_with("IF") ||
                         order.instrument_id.starts_with("IC") ||
                         order.instrument_id.starts_with("IH") ||
                         order.instrument_id.starts_with("IM") ||
                         order.instrument_id.starts_with("TS") ||
                         order.instrument_id.starts_with("TF") ||
                         order.instrument_id.starts_with("T") => "CFFEX",

                    // 大商所 (DCE) - 通常是小写字母
                    "a" | "b" | "c" | "cs" | "i" | "j" | "jm" | "l" | "m" | "p" | "pp" | "v" | "y" |
                    "bb" | "fb" | "jd" | "lh" | "pg" | "rr" | "eb" => "DCE",

                    // 郑商所 (CZCE) - 通常是大写字母开头
                    _ if order.instrument_id.len() >= 2 => {
                        let upper_prefix = order.instrument_id.chars().take(2).collect::<String>().to_uppercase();
                        match upper_prefix.as_str() {
                            "CF" | "CY" | "FG" | "MA" | "OI" | "RM" | "SF" | "SM" | "SR" | "TA" | "ZC" |
                            "AP" | "CJ" | "LR" | "JR" | "PM" | "RI" | "RS" | "WH" | "PK" | "UR" | "SA" => "CZCE",
                            _ => "", // 让CTP自动处理
                        }
                    },
                    _ => "", // 让CTP自动处理
                }
            } else {
                "" // 合约代码太短，让CTP自动处理
            };

            if !exchange_id.is_empty() {
                copy_str_to_ctp_array(exchange_id, &mut input_order.ExchangeID);
                println!("📤 [DEBUG] Set ExchangeID: {}", exchange_id);
            } else {
                println!("📤 [DEBUG] ExchangeID not set, let CTP auto-detect");
            }

            // 详细的调试日志
            println!("📤 [DEBUG] Order details:");
            println!("  - BrokerID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.BrokerID));
            println!("  - InvestorID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.InvestorID));
            println!("  - InstrumentID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.InstrumentID));
            println!("  - OrderRef: {}", order_ref);
            println!("  - UserID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.UserID));
            println!("  - Direction: {} ({})", input_order.Direction, if input_order.Direction == THOST_FTDC_D_Buy as i8 { "买入" } else { "卖出" });
            println!("  - OrderPriceType: {} ({})", input_order.OrderPriceType, if input_order.OrderPriceType == THOST_FTDC_OPT_LimitPrice as i8 { "限价" } else { "市价" });
            println!("  - LimitPrice: {}", input_order.LimitPrice);
            println!("  - VolumeTotalOriginal: {}", input_order.VolumeTotalOriginal);
            println!("  - CombOffsetFlag[0]: {}", input_order.CombOffsetFlag[0]);
            println!("  - CombHedgeFlag[0]: {}", input_order.CombHedgeFlag[0]);
            println!("  - TimeCondition: {}", input_order.TimeCondition);
            println!("  - VolumeCondition: {}", input_order.VolumeCondition);
            println!("  - ContingentCondition: {}", input_order.ContingentCondition);
            println!("  - ForceCloseReason: {}", input_order.ForceCloseReason);
            println!("  - MinVolume: {}", input_order.MinVolume);
            println!("  - IsAutoSuspend: {}", input_order.IsAutoSuspend);
            println!("  - UserForceClose: {}", input_order.UserForceClose);
            println!("  - IsSwapOrder: {}", input_order.IsSwapOrder);
            println!("  - ExchangeID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&input_order.ExchangeID));
            println!("  - RequestID: {}", input_order.RequestID);

            println!("📤 [DEBUG] Calling ReqOrderInsert with order_ref: {}, request_id: {}", order_ref, request_id);

            // 清除之前的订单插入结果
            {
                let mut order_results = ORDER_INSERT_RESULTS.lock().unwrap();
                order_results.remove(&order_ref);
            }

            // 调用CTP API插入订单
            let result = api.req_order_insert(&mut input_order, request_id);

            if result == 0 {
                println!("✅ [DEBUG] ReqOrderInsert request sent successfully");
                Ok(format!("订单已成功提交，订单引用: {}", order_ref))
            } else {
                println!("❌ [DEBUG] ReqOrderInsert failed with code: {}", result);
                Err(format!("提交订单失败，错误代码: {}", result))
            }
        } else {
            Err("未找到交易API会话或登录信息".to_string())
        }
    }) {
        Ok(Ok(message)) => ApiResponse {
            success: true,
            data: Some(message),
            error: None,
        },
        Ok(Err(error)) => ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        },
        Err(_) => ApiResponse {
            success: false,
            data: None,
            error: Some("插入订单时发生系统错误".to_string()),
        },
    }
}

// 诊断订单字段问题
#[command]
pub fn diagnose_order_fields(
    session_id: String,
    order: OrderRequest,
) -> ApiResponse<serde_json::Value> {
    println!("🔍 [DEBUG] diagnose_order_fields called with session_id: {}, order: {:?}", session_id, order);

    let mut diagnosis = serde_json::Map::new();

    // 1. 检查会话状态
    let session_valid = {
        let apis = TRADER_APIS.lock().unwrap();
        apis.contains_key(&session_id)
    };
    diagnosis.insert("session_valid".to_string(), serde_json::Value::Bool(session_valid));

    // 2. 检查登录状态
    let login_status = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&session_id).copied().unwrap_or(false)
    };
    diagnosis.insert("login_status".to_string(), serde_json::Value::Bool(login_status));

    // 3. 验证订单字段
    let field_validation = match validate_order_fields(&order) {
        Ok(_) => serde_json::json!({"valid": true, "message": "所有字段验证通过"}),
        Err(error) => serde_json::json!({"valid": false, "message": error}),
    };
    diagnosis.insert("field_validation".to_string(), field_validation);

    // 4. 检查合约代码格式
    let instrument_analysis = analyze_instrument_id(&order.instrument_id);
    diagnosis.insert("instrument_analysis".to_string(), instrument_analysis);

    // 5. 提供修复建议
    let mut suggestions = Vec::new();
    if !session_valid {
        suggestions.push("请先创建交易API会话".to_string());
    }
    if !login_status {
        suggestions.push("请先完成交易登录".to_string());
    }
    if order.price <= 0.0 {
        suggestions.push("价格必须大于0".to_string());
    }
    if order.volume <= 0 {
        suggestions.push("数量必须大于0".to_string());
    }

    diagnosis.insert("suggestions".to_string(), serde_json::Value::Array(
        suggestions.into_iter().map(serde_json::Value::String).collect()
    ));

    ApiResponse {
        success: true,
        data: Some(serde_json::Value::Object(diagnosis)),
        error: None,
    }
}

// 分析合约代码
fn analyze_instrument_id(instrument_id: &str) -> serde_json::Value {
    let mut analysis = serde_json::Map::new();

    analysis.insert("original".to_string(), serde_json::Value::String(instrument_id.to_string()));
    analysis.insert("length".to_string(), serde_json::Value::Number(serde_json::Number::from(instrument_id.len())));

    if instrument_id.len() >= 2 {
        let prefix = instrument_id.chars().take(2).collect::<String>();
        analysis.insert("prefix".to_string(), serde_json::Value::String(prefix.clone()));

        // 推断交易所
        let exchange = if instrument_id.len() >= 2 {
            let prefix_lower = prefix.to_lowercase();
            match prefix_lower.as_str() {
                "rb" | "hc" | "ss" | "wr" | "fu" | "bu" | "ru" | "sp" | "au" | "ag" |
                "cu" | "al" | "zn" | "pb" | "ni" | "sn" | "sc" | "lu" | "bc" | "nr" => "SHFE",
                _ if instrument_id.starts_with("IF") || instrument_id.starts_with("IC") ||
                     instrument_id.starts_with("IH") || instrument_id.starts_with("IM") => "CFFEX",
                "a" | "b" | "c" | "cs" | "i" | "j" | "jm" | "l" | "m" | "p" | "pp" | "v" | "y" => "DCE",
                _ => {
                    let upper_prefix = prefix.to_uppercase();
                    match upper_prefix.as_str() {
                        "CF" | "CY" | "FG" | "MA" | "OI" | "RM" | "SF" | "SM" | "SR" | "TA" | "ZC" => "CZCE",
                        _ => "UNKNOWN",
                    }
                }
            }
        } else {
            "UNKNOWN"
        };

        analysis.insert("detected_exchange".to_string(), serde_json::Value::String(exchange.to_string()));

        // 检查格式是否合理
        let format_valid = instrument_id.len() >= 4 && instrument_id.len() <= 8;
        analysis.insert("format_valid".to_string(), serde_json::Value::Bool(format_valid));
    }

    serde_json::Value::Object(analysis)
}

#[command]
pub fn cancel_order(
    session_id: String,
    cancel_request: CancelOrderRequest,
) -> ApiResponse<String> {
    println!("🔍 [DEBUG] cancel_order called with session_id: {}, cancel_request: {:?}", session_id, cancel_request);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = TRADER_APIS.lock().unwrap();
        let login_info = SESSION_LOGIN_INFO.lock().unwrap();

        if let (Some(api), Some(account_config)) = (apis.get_mut(&session_id), login_info.get(&session_id)) {
            println!("✅ [DEBUG] Found Trader API and login info for session: {}", session_id);

            // 引入CTP相关类型
            use ctp_trade_lib::*;

            // 创建输入报单操作结构
            let mut input_order_action = CThostFtdcInputOrderActionField::default();

            // 填充基本信息
            copy_str_to_ctp_array(&account_config.broker_id, &mut input_order_action.BrokerID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order_action.InvestorID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order_action.UserID);
            copy_str_to_ctp_array(&cancel_request.instrument_id, &mut input_order_action.InstrumentID);
            copy_str_to_ctp_array(&cancel_request.order_ref, &mut input_order_action.OrderRef);

            // 设置操作引用 (OrderActionRef是整数类型)
            let action_ref = get_next_order_ref();
            input_order_action.OrderActionRef = action_ref.parse::<i32>().unwrap_or(1);

            // 设置操作标志为删除
            input_order_action.ActionFlag = THOST_FTDC_AF_Delete as i8;

            // 动态获取FrontID和SessionID
            if let Some((front_id, session_id_num)) = get_session_front_and_session_id(&session_id) {
                input_order_action.FrontID = front_id;
                input_order_action.SessionID = session_id_num;
                println!("📤 [DEBUG] 动态获取到FrontID: {}, SessionID: {}", front_id, session_id_num);
            } else {
                // 如果没有会话级别的，尝试从订单级别获取
                let front_session_map = ORDER_FRONT_SESSION_MAP.lock().unwrap();
                if let Some((front_id, session_id_num)) = front_session_map.get(&cancel_request.order_ref) {
                    input_order_action.FrontID = *front_id;
                    input_order_action.SessionID = *session_id_num;
                    println!("📤 [DEBUG] 从订单获取到FrontID: {}, SessionID: {}", front_id, session_id_num);
                } else {
                    println!("⚠️ [DEBUG] 未找到FrontID和SessionID，让CTP自动处理");
                }
            }

            // 设置交易所代码（必须设置）
            if let Some(exchange_id) = &cancel_request.exchange_id {
                copy_str_to_ctp_array(exchange_id, &mut input_order_action.ExchangeID);
            }

            // 不设置OrderSysID，使用OrderRef进行撤单
            // copy_str_to_ctp_array("", &mut input_order_action.OrderSysID);

            // 获取请求ID
            let request_id = get_next_request_id();

            println!("📤 [DEBUG] 撤单详细参数:");
            println!("  - BrokerID: {}", account_config.broker_id);
            println!("  - InvestorID: {}", account_config.account);
            println!("  - InstrumentID: {}", cancel_request.instrument_id);
            println!("  - OrderRef: {}", cancel_request.order_ref);
            println!("  - ActionRef: {}", action_ref);
            println!("  - ExchangeID: {:?}", cancel_request.exchange_id);
            println!("  - FrontID: {}", input_order_action.FrontID);
            println!("  - SessionID: {}", input_order_action.SessionID);
            println!("  - OrderSysID: {:?}", cancel_request.order_sys_id);
            println!("  - ActionFlag: Delete");
            println!("  - RequestID: {}", request_id);

            println!("📤 [DEBUG] Calling ReqOrderAction with order_ref: {}, action_ref: {}, request_id: {}",
                     cancel_request.order_ref, action_ref, request_id);

            // 调用CTP API撤销订单
            let result = api.req_order_action(&mut input_order_action, request_id);

            if result == 0 {
                println!("✅ [DEBUG] ReqOrderAction successful");
                Ok(format!("撤单请求已提交，订单引用: {}, 操作引用: {}", cancel_request.order_ref, action_ref))
            } else {
                println!("❌ [DEBUG] ReqOrderAction failed with code: {}", result);
                Err(format!("提交撤单失败，错误代码: {}", result))
            }
        } else {
            Err("未找到交易API会话或登录信息".to_string())
        }
    }) {
        Ok(Ok(message)) => ApiResponse {
            success: true,
            data: Some(message),
            error: None,
        },
        Ok(Err(error)) => ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        },
        Err(_) => ApiResponse {
            success: false,
            data: None,
            error: Some("撤销订单时发生系统错误".to_string()),
        },
    }
}

// 获取当前活跃的trader session
#[command]
pub fn get_active_trader_session() -> ApiResponse<String> {
    let login_status = TRADER_LOGIN_STATUS.lock().unwrap();

    // 找到第一个已登录的session
    for (session_id, is_logged_in) in login_status.iter() {
        if *is_logged_in {
            return ApiResponse {
                success: true,
                data: Some(session_id.clone()),
                error: None,
            };
        }
    }

    ApiResponse {
        success: false,
        data: None,
        error: Some("未找到活跃的交易会话".to_string()),
    }
}

// 测试订单接口
#[command]
pub async fn test_order_interface(session_id: String) -> ApiResponse<String> {
    println!("🧪 [TEST] Starting order interface test for session: {}", session_id);

    // 如果传入的session_id为空，尝试获取活跃的session
    let actual_session_id = if session_id.is_empty() {
        let active_session_result = get_active_trader_session();
        if active_session_result.success {
            active_session_result.data.unwrap_or_default()
        } else {
            return ApiResponse {
                success: false,
                data: None,
                error: Some("未找到活跃的交易会话，请先登录".to_string()),
            };
        }
    } else {
        session_id
    };

    println!("🧪 [TEST] Using session: {}", actual_session_id);

    // 检查登录状态
    let is_logged_in = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&actual_session_id).unwrap_or(&false).clone()
    };

    if !is_logged_in {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("请先登录CTP交易系统".to_string()),
        };
    }

    let mut test_results = Vec::new();

    // 测试1: 挂单测试
    println!("🧪 [TEST] Testing order insert...");
    let test_order = OrderRequest {
        instrument_id: "rb2509".to_string(), // 使用螺纹钢主力合约
        direction: "0".to_string(), // 买入
        price: 3500.0, // 测试价格
        volume: 1, // 1手
        order_type: "2".to_string(), // 限价单（修正为"2"）
        offset_flag: Some("0".to_string()), // 开仓
        hedge_flag: Some("1".to_string()), // 投机
        time_condition: Some("3".to_string()), // 当日有效
        volume_condition: Some("1".to_string()), // 任何数量
    };

    let insert_result = insert_order(actual_session_id.clone(), test_order);
    if insert_result.success {
        test_results.push("✅ 挂单测试成功".to_string());
        println!("✅ [TEST] Order insert test passed: {}", insert_result.data.unwrap_or_default());

        // 等待一下让订单处理
        tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await;

        // 测试2: 撤单测试（使用刚才的订单引用）
        println!("🧪 [TEST] Testing order cancel...");

        // 获取最新的订单引用（简化处理，实际应该从订单回调中获取）
        let order_ref = {
            let counter = ORDER_REF_COUNTER.lock().unwrap();
            format!("{}", *counter - 1) // 使用上一个订单引用
        };

        let cancel_request = CancelOrderRequest {
            instrument_id: "rb2509".to_string(),
            order_ref: order_ref.clone(),
            front_id: None,
            session_id: None,
            exchange_id: Some("SHFE".to_string()), // 上海期货交易所
            order_sys_id: None,
        };

        let cancel_result = cancel_order(actual_session_id.clone(), cancel_request);
        if cancel_result.success {
            test_results.push("✅ 撤单测试成功".to_string());
            println!("✅ [TEST] Order cancel test passed: {}", cancel_result.data.unwrap_or_default());
        } else {
            let error_msg = cancel_result.error.unwrap_or_default();
            test_results.push(format!("❌ 撤单测试失败: {}", error_msg));
            println!("❌ [TEST] Order cancel test failed: {}", error_msg);
        }
    } else {
        let error_msg = insert_result.error.unwrap_or_default();
        test_results.push(format!("❌ 挂单测试失败: {}", error_msg));
        println!("❌ [TEST] Order insert test failed: {}", error_msg);
    }

    let summary = format!("订单接口测试完成:\n{}", test_results.join("\n"));
    println!("🧪 [TEST] Order interface test completed");

    ApiResponse {
        success: true,
        data: Some(summary),
        error: None,
    }
}

// 查询账户资金
#[command]
pub fn query_account(
    session_id: String,
) -> ApiResponse<AccountInfo> {
    println!("🔍 [DEBUG] query_account called with session_id: {}", session_id);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let apis = TRADER_APIS.lock().unwrap();

        if let Some(_api) = apis.get(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 注意：这里应该调用真实的CTP查询账户API
            // 由于当前的实现是基于异步流的，这里返回模拟数据
            let account_info = AccountInfo {
                broker_id: "9999".to_string(),
                account_id: "test_account".to_string(),
                pre_mortgage: 0.0,
                pre_credit: 0.0,
                pre_deposit: 0.0,
                pre_balance: 100000.0,
                pre_margin: 0.0,
                interest_base: 0.0,
                interest: 0.0,
                deposit: 0.0,
                withdraw: 0.0,
                frozen_margin: 0.0,
                frozen_cash: 0.0,
                frozen_commission: 0.0,
                curr_margin: 0.0,
                cash_in: 0.0,
                commission: 0.0,
                close_profit: 0.0,
                position_profit: 0.0,
                balance: 100000.0,
                available: 95000.0,
                withdraw_quota: 95000.0,
                reserve: 0.0,
                trading_day: "20241221".to_string(),
                settlement_id: 1,
                credit: 0.0,
                mortgage: 0.0,
                exchange_margin: 0.0,
                delivery_margin: 0.0,
                exchange_delivery_margin: 0.0,
                reserve_balance: 0.0,
                currency_id: "CNY".to_string(),
                pre_fund_mortgage_in: 0.0,
                pre_fund_mortgage_out: 0.0,
                fund_mortgage_in: 0.0,
                fund_mortgage_out: 0.0,
                fund_mortgage_available: 0.0,
                mortgage_able_fund: 0.0,
                spec_product_margin: 0.0,
                spec_product_frozen_margin: 0.0,
                spec_product_commission: 0.0,
                spec_product_frozen_commission: 0.0,
                spec_product_position_profit: 0.0,
                spec_product_close_profit: 0.0,
                spec_product_position_profit_by_alg: 0.0,
                spec_product_exchange_margin: 0.0,
                bis_margin: 0.0,
                bis_frozen_margin: 0.0,
                bis_commission: 0.0,
                bis_frozen_commission: 0.0,
                bis_position_profit: 0.0,
                bis_close_profit: 0.0,
                bis_position_profit_by_alg: 0.0,
                bis_exchange_margin: 0.0,
                frozen_swap: 0.0,
                remain_swap: 0.0,
            };

            Ok(account_info)
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(account_info)) => {
            println!("✅ [SUCCESS] Account query successful");
            ApiResponse {
                success: true,
                data: Some(account_info),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Account query failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Account query panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 查询持仓信息
#[command]
pub fn query_position(
    session_id: String,
) -> ApiResponse<Vec<PositionInfo>> {
    println!("🔍 [DEBUG] query_position called with session_id: {}", session_id);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let apis = TRADER_APIS.lock().unwrap();

        if let Some(_api) = apis.get(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 注意：这里应该调用真实的CTP查询持仓API
            // 由于当前的实现是基于异步流的，这里返回模拟数据
            let positions = vec![
                PositionInfo {
                    instrument_id: "rb2509".to_string(),
                    broker_id: "9999".to_string(),
                    investor_id: "test_account".to_string(),
                    posi_direction: "2".to_string(), // 2=多头, 3=空头
                    hedge_flag: "1".to_string(),
                    position_date: "1".to_string(),
                    yd_position: 0,
                    position: 2,
                    long_frozen: 0,
                    short_frozen: 0,
                    long_frozen_amount: 0.0,
                    short_frozen_amount: 0.0,
                    open_volume: 2,
                    close_volume: 0,
                    open_amount: 6140.0,
                    close_amount: 0.0,
                    position_cost: 6140.0,
                    pre_margin: 0.0,
                    use_margin: 1228.0,
                    frozen_margin: 0.0,
                    frozen_cash: 0.0,
                    frozen_commission: 0.0,
                    cash_in: 0.0,
                    commission: 12.0,
                    close_profit: 0.0,
                    position_profit: -40.0,
                    pre_settlement_price: 3070.0,
                    settlement_price: 3070.0,
                    trading_day: "20241221".to_string(),
                    settlement_id: 1,
                    open_cost: 6140.0,
                    exchange_margin: 1228.0,
                    comb_position: 0,
                    comb_long_frozen: 0,
                    comb_short_frozen: 0,
                    close_profit_by_date: 0.0,
                    close_profit_by_trade: 0.0,
                    today_position: 2,
                    margin_rate_by_money: 0.2,
                    margin_rate_by_volume: 0.0,
                    strike_frozen: 0,
                    strike_frozen_amount: 0.0,
                    abandon_frozen: 0,
                    exchange_id: "SHFE".to_string(),
                    yd_strike_frozen: 0,
                    invest_unit_id: "".to_string(),
                    position_cost_offset: 0.0,
                    tas_position: 0,
                    tas_position_cost: 0.0,
                }
            ];

            Ok(positions)
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(positions)) => {
            println!("✅ [SUCCESS] Position query successful, {} positions", positions.len());
            ApiResponse {
                success: true,
                data: Some(positions),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Position query failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Position query panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}





// 全局查询请求计数器，用于生成唯一的请求ID
static mut QUERY_REQUEST_ID: i32 = 1;


// 查询合约信息 - 完全通过真实CTP API获取
#[command]
pub async fn query_instruments(
    session_id: String,
) -> ApiResponse<Vec<InstrumentInfo>> {
    println!("🔍 [DEBUG] query_instruments called with session_id: {}", session_id);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = TRADER_APIS.lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 真实调用CTP查询接口
            use ctp_trade_lib::*;

            // 创建查询合约请求结构
            let mut req = CThostFtdcQryInstrumentField::default();

            // 获取唯一的请求ID
            let request_id = get_next_request_id();

            println!("🔍 [INFO] Starting real CTP instrument query with request_id: {}", request_id);

            // 添加延迟以避免查询频率过快
            std::thread::sleep(std::time::Duration::from_millis(1000));

            // 调用查询合约接口
            let result = api.req_qry_instrument(&mut req, request_id);

            if result == 0 {
                println!("✅ [SUCCESS] CTP req_qry_instrument called successfully, waiting for callback...");

                // 重置查询状态
                {
                    let mut query_complete = INSTRUMENTS_QUERY_COMPLETE.lock().unwrap();
                    *query_complete = false;

                    let mut instruments_data = CTP_INSTRUMENTS_DATA.lock().unwrap();
                    instruments_data.clear();
                }

                // 等待回调完成，设置合理的超时时间
                let mut wait_count = 0;
                let max_wait = 300; // 30秒，每次等待100ms
                let progress_interval = 50; // 每5秒打印一次进度

                println!("⏳ [INFO] Waiting for CTP instrument query callback...");

                loop {
                    std::thread::sleep(std::time::Duration::from_millis(100));
                    wait_count += 1;

                    // 每5秒打印一次进度
                    if wait_count % progress_interval == 0 {
                        let elapsed_seconds = wait_count / 10;
                        println!("⏳ [PROGRESS] Waiting for CTP response... {}s elapsed", elapsed_seconds);
                    }

                    let query_complete = INSTRUMENTS_QUERY_COMPLETE.lock().unwrap();
                    if *query_complete {
                        drop(query_complete);

                        let instruments_data = CTP_INSTRUMENTS_DATA.lock().unwrap();
                        let result_data = instruments_data.clone();
                        drop(instruments_data);

                        if result_data.len() > 0 {
                            println!("✅ [SUCCESS] CTP query completed, found {} real instruments", result_data.len());
                            return Ok(result_data);
                        } else {
                            println!("⚠️ [WARNING] CTP query completed but no instruments found");
                            break;
                        }
                    }

                    if wait_count >= max_wait {
                        println!("⏰ [TIMEOUT] CTP query timeout after 30 seconds");
                        return Err("CTP合约查询超时（30秒），请检查网络连接和CTP服务状态".to_string());
                    }
                }

                // 如果查询完成但没有数据
                println!("⚠️ [NO_DATA] CTP query completed but no instruments found");
                return Err("CTP合约查询完成但未获取到任何合约数据".to_string());
            } else {
                println!("❌ [ERROR] CTP req_qry_instrument failed with code: {}", result);

                // 根据错误代码提供详细信息
                let error_msg = match result {
                    -1 => "网络连接错误或API未正确连接",
                    -2 => "未处理请求超过许可数，请稍后重试",
                    -3 => "每秒发送请求数超过许可数，请降低请求频率",
                    _ => "未知错误"
                };

                println!("❌ [QUERY_FAILED] CTP query failed: {}", error_msg);
                return Err(format!("CTP合约查询失败: {}", error_msg));
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(instruments)) => {
            println!("✅ [SUCCESS] Instruments query initiated, {} instruments", instruments.len());
            ApiResponse {
                success: true,
                data: Some(instruments),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Instruments query failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Instruments query panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 获取当前会话的FrontID和SessionID
fn get_session_front_and_session_id(session_id: &str) -> Option<(i32, i32)> {
    let front_session_map = ORDER_FRONT_SESSION_MAP.lock().unwrap();
    let session_key = format!("session_{}", session_id);
    front_session_map.get(&session_key).copied()
}

// 查询当前会话的FrontID和SessionID
#[command]
pub async fn get_session_info(session_id: String) -> ApiResponse<String> {
    if let Some((front_id, session_id_num)) = get_session_front_and_session_id(&session_id) {
        let info = format!("FrontID: {}, SessionID: {}", front_id, session_id_num);
        println!("🔍 [DEBUG] 查询会话信息: {}", info);
        ApiResponse {
            success: true,
            data: Some(info),
            error: None,
        }
    } else {
        let error = "未找到会话信息".to_string();
        println!("⚠️ [DEBUG] {}", error);
        ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        }
    }
}

// 订单信息结构
#[derive(Debug, Clone, serde::Serialize)]
pub struct OrderInfo {
    pub order_ref: String,
    pub instrument_id: String,
    pub direction: String,
    pub price: f64,
    pub volume: i32,
    pub volume_traded: i32,
    pub order_status: String,
    pub front_id: i32,
    pub session_id: i32,
}



// 查询账号下所有未成交订单
#[command]
pub async fn query_all_orders(session_id: String) -> ApiResponse<Vec<OrderInfo>> {
    println!("🔍 [DEBUG] query_all_orders called with session_id: {}", session_id);

    // 检查登录状态
    let is_logged_in = {
        let login_status = TRADER_LOGIN_STATUS.lock().unwrap();
        login_status.get(&session_id).unwrap_or(&false).clone()
    };

    if !is_logged_in {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("请先登录CTP交易系统".to_string()),
        };
    }

    // 检查Trader API是否存在
    let api_exists = {
        let apis = TRADER_APIS.lock().unwrap();
        apis.contains_key(&session_id)
    };

    if !api_exists {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("未找到Trader API".to_string()),
        };
    }

    // 获取登录信息
    let login_info = {
        let login_infos = SESSION_LOGIN_INFO.lock().unwrap();
        login_infos.get(&session_id).cloned()
    };

    let account_config = match login_info {
        Some(config) => config,
        None => {
            return ApiResponse {
                success: false,
                data: None,
                error: Some("未找到登录信息".to_string()),
            };
        }
    };

    // 生成请求ID
    let request_id = {
        let mut counter = REQUEST_ID_COUNTER.lock().unwrap();
        *counter += 1;
        *counter
    };

    // 创建查询订单请求
    let mut req = ctp_trade_lib::CThostFtdcQryOrderField::default();

    // 设置查询参数
    unsafe {
        std::ptr::copy_nonoverlapping(
            account_config.broker_id.as_ptr(),
            req.BrokerID.as_mut_ptr() as *mut u8,
            std::cmp::min(account_config.broker_id.len(), req.BrokerID.len() - 1),
        );

        std::ptr::copy_nonoverlapping(
            account_config.account.as_ptr(),
            req.InvestorID.as_mut_ptr() as *mut u8,
            std::cmp::min(account_config.account.len(), req.InvestorID.len() - 1),
        );
    }

    println!("🔍 [DEBUG] 查询订单参数:");
    println!("  - BrokerID: {}", account_config.broker_id);
    println!("  - InvestorID: {}", account_config.account);
    println!("  - RequestID: {}", request_id);

    // 清空之前的查询结果
    {
        let mut queried_orders = QUERIED_ORDERS.lock().unwrap();
        queried_orders.insert(session_id.clone(), Vec::new());
    }

    // 调用CTP查询接口
    let result = {
        let mut apis = TRADER_APIS.lock().unwrap();
        if let Some(api) = apis.get_mut(&session_id) {
            api.req_qry_order(&mut req, request_id)
        } else {
            -1
        }
    };

    if result == 0 {
        println!("✅ [DEBUG] 订单查询请求发送成功，等待响应...");

        // 等待查询结果（最多等待3秒）
        for i in 0..30 {
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

            let queried_orders = QUERIED_ORDERS.lock().unwrap();
            if let Some(orders) = queried_orders.get(&session_id) {
                if !orders.is_empty() || i >= 29 {
                    let orders_clone = orders.clone();
                    drop(queried_orders);

                    println!("✅ [DEBUG] 查询到 {} 个订单", orders_clone.len());
                    return ApiResponse {
                        success: true,
                        data: Some(orders_clone),
                        error: None,
                    };
                }
            }
        }

        // 超时或无订单
        ApiResponse {
            success: true,
            data: Some(Vec::new()),
            error: None,
        }
    } else {
        let error_msg = format!("订单查询请求失败，错误代码: {}", result);
        println!("❌ [DEBUG] {}", error_msg);
        ApiResponse {
            success: false,
            data: None,
            error: Some(error_msg),
        }
    }
}